Solve a transcendental equation#

Solve

\[ x = \cos(x) \]

for \(x\)

import sympy as sym

x = sym.symbols(("x"))

Q = x-sym.cos(x)
I = sym.solveset(Q,domain = sym.Reals)
I
\[\displaystyle \left\{x\; \middle|\; x \in \mathbb{R} \wedge x - \cos{\left(x \right)} = 0 \right\}\]
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.735,0.74)

def f(x):
    return x-np.cos(x)

plt.plot(x,f(x))
plt.grid()
plt.show()
../_images/Untitled_2_0.png
xguess = 0.739
f(xguess)
-0.00014247729458616298
x1 = 0.738
x2 = 0.74

print(f(x1),f(x2))

x3 = 0.5*(x1+x2)

print(x3,f(x3))
-0.0018156567171687676 0.0015314412704120484
0.739 -0.00014247729458616298
x1 = 0.5
x2 = 1.0

for i in range(50):
    x3 = 0.5*(x1+x2)
    if(np.abs(f(x3))<1.e-15):
        print(i,x3,f(x3))
        break
    elif(f(x3)<0):
        x1 = x3
    else:
        x2 = x3
47 0.7390851332151609 4.440892098500626e-16
plt.plot(x,f(x))
plt.plot(x3,f(x3),'o')
plt.grid()
plt.show()
../_images/Untitled_6_0.png