Saturday, October 29, 2022

Solving one transcendental equation via SciPy

Решение уравнения  x*np.cos(x)-(1-x)**(0.5) = 0

(.env) boris@UbuntuLTS:~/CURVE$ cat solveSci3.py

import numpy as np

import matplotlib.pyplot as plt

from scipy.optimize import fsolve

func = lambda x : (x*np.cos(x)-(1-x)**(0.5)) 

# Plot it

x = np.linspace(-5,1,100 )

plt.plot(x, func(x))

plt.xlabel("x")

plt.ylabel("expression value")

plt.grid()

plt.draw()

# Use the numerical solver to find the roots

x_initial_guess = -5

x_solution = fsolve(func, x_initial_guess)

print("The solution is x = %f" % x_solution)

print("at which the value of the expression is %f" % func(x_solution))

x_initial_guess = -3

x_solution = fsolve(func, x_initial_guess)

print("The solution is x = %f" % x_solution)

print("at which the value of the expression is %f" % func(x_solution))

x_initial_guess = 0

x_solution = fsolve(func, x_initial_guess)

print("The solution is x = %f" % x_solution)

print("at which the value of the expression is %f" % func(x_solution))


plt.show()



























Final draft

(.env) boris@UbuntuLTS:~/CURVE$ cat solveSci.py

import numpy as np

import matplotlib.pyplot as plt

from scipy.optimize import fsolve


func = lambda x : - (x*np.cos(x)-(1-x)**(0.5)) 


# Plot it

   x = np.linspace(-5,1,100 )

   fig, ax = plt.subplots()


   ax.plot(x, func(x))

   ax.hlines(y=0.0,xmin=-5, xmax=2, linewidth=2, color='r')

   ax.vlines(x=-5.0,ymin=-4, ymax=4,linewidth=2, color='r')

   ax.vlines(x=1.0,ymin=-4, ymax=4,linewidth=2, color='r')


  plt.xlabel("x")

  plt.ylabel("expression value")

  plt.grid()

  plt.draw()


# Use the numerical solver to find the roots

x_initial_guess = -5

x_solution = fsolve(func, x_initial_guess)

print("The solution is x = %f" % x_solution)

print("at which the value of the expression is %f" % func(x_solution))

ax.vlines(x=x_solution,ymin=-4, ymax=4,linewidth=2, color='blue')


x_initial_guess = -3

x_solution = fsolve(func, x_initial_guess)

print("The solution is x = %f" % x_solution)

print("at which the value of the expression is %f" % func(x_solution))

ax.vlines(x=x_solution,ymin=-4, ymax=4,linewidth=2, color='blue')


x_initial_guess = 0

x_solution = fsolve(func, x_initial_guess)

print("The solution is x = %f" % x_solution)

print("at which the value of the expression is %f" % func(x_solution))

ax.vlines(x=x_solution,ymin=-4, ymax=4,linewidth=2, color='blue')


plt.show()




















No comments:

Post a Comment