import math
# These choices depend on the problem being solved
x0 = .1 # The initial value
R = 3.81
A = 2.17
def f(x):
return R**2*(x - math.sin(x))/2 - A
def fprime(x):
return R**2*(1 - math.cos(x))/2
def altezza(x):
return R - R * math.cos(x/2)
TOLERANCE = 1E-7 # 7 digit accuracy is desired
EPSILON = 1E-14 # Don't want to divide by a number smaller than this
MAX_ITERATIONS = 20 # Don't allow the iterations to continue indefinitely
found_solution = False # Have not converged to a solution yet
for i in range(MAX_ITERATIONS):
y = f(x0)
yprime = fprime(x0)
# Don't want to divide by too small of a number
# denominator is too small
if abs(yprime) < EPSILON:
break # Leave the loop
x1 = x0 - y / yprime # Do Newton's computation
# If the result is within the desired tolerance
if abs(x1 - x0) <= TOLERANCE * abs(x1):
found_solution = True
break # Done, so leave the loop
x0 = x1 # Update x0 to start the process again
if found_solution:
# x1 is a solution within tolerance and maximum number of iterations
print("Numero iterazioni:",i)
print("x1 in rad:",x1)
print("x1 in gradi:",math.degrees(x1))
print ("Altezza:",altezza(x1))
else:
# did not converge
print("Non converge")