Find the numerical solution of the following nonlinear equations using the dichotomy and Newton's method.
sin(x)=0
When $ f (x) $ is continuous and $ f (a) f (b) <0 $ in the interval $ x = [a, b] $, the solution that $ f (x) = 0 $ in the interval How to find one.
The algorithm is
In order to find the solution of $ x = π $, the initial values are $ a_0 = 3.0 $ and $ b_0 = 3.5 $.
import math
def f(x):
return math.sin(x)
EPS1 = 0.00001
EPS2 = 0.00001
a = 3.0
b = 3.5
while True:
c = (a + b)/2
if f(a)*f(c) < 0:
b = c
else:
a = c
if abs(f(c)) < EPS1 or abs(a - b) < EPS2:
break
print("x = %f" % c)
>>> print("x = %f" % c)
x = 3.141602
A method of finding the tangent of $ f (x) $ in $ x_i $, updating the intersection of the tangent and the $ x $ axis as the next $ x_ {i + 1} $, and performing sequential calculations.
The tangent $ g (x) $ of $ f (x) $ in $ x_i $ is
g(x)-f(x_i)=f^{'}(x_i)(x-x_i)
Set $ g (x) = 0 $ to update the intersection of the tangent and the $ x $ axis as the next $ x_ {i + 1} $
0-f(x_i) = f^{'}(x_i)(x_{i+1}-x_i)\\
x_{i+1} = x_i-\frac{f(x_i)}{f^{'}(x_i)} ... ①
The algorithm is
This time, the analytical solution ($ cos (x) $) was used as the differential value.
import math
def f(x):
return math.sin(x)
def df(x):
return math.cos(x)
EPS1 = 0.0001
x = 3.5
while True:
x -= f(x)/df(x)
if abs(f(x)) < EPS1:
break
print("x = %f" % x)
>>> print("x = %f" % x)
x = 3.141594