Home > Blockchain >  Cant plot an equation properly in Python
Cant plot an equation properly in Python

Time:01-07

I am trying to plot a 3rd rank polynomial that I calculated through Lagrance with a given set of x,y.(x=P_Maz , y=H_Maz).I can't really find what I am doing wrong.Even some plots I tried would show me wrong graph(Because x=0 wouldnt give y=25). The equation is as follows:

           3            2
3.395e-06 x - 0.001528 x   1.976 x   25

The part of my function and plot is this one:

P_Maz = np.array([120, 180, 270, 300])  # x
H_Maz = np.array([246, 351, 514, 572])  # y

def Lagrange(Lx, Ly):
    x = symbols('x')
    y = 0
    for k in range(len(Lx)):
        p = 1
        for j in range(len(Lx)):
            if j != k:
                p = p * ((x - Lx[j]) / (Lx[k] - Lx[j]))
        y  = p * Ly[k]
    return y

poly1=simplify(Lagrange(P_Maz,H_Maz))

plot(P_Maz,poly1(H_Maz))
grid()
show()

I get the following error:

Traceback (most recent call last):
  File "C:\Users\Egw\Desktop\Analysh\Askhsh1\askhsh5.py", line 36, in <module>
    plot(P_Maz,poly1(H_Maz))
TypeError: 'Add' object is not callable

Full code is as follows:

import numpy as np
from matplotlib.pyplot import plot, show, grid
import numpy.polynomial.polynomial as poly
import matplotlib.pyplot as plt
from scipy.interpolate import lagrange
from sympy import symbols, Eq,simplify

P_Maz = np.array([120, 180, 270, 300])  # x
H_Maz = np.array([246, 351, 514, 572])  # y
P_Lig = np.array([150, 215, 285, 300])  # x
H_Lig = np.array([307, 427, 563, 594])  # y


def Lagrange(Lx, Ly):
    x = symbols('x')
    y = 0
    for k in range(len(Lx)):
        p = 1
        for j in range(len(Lx)):
            if j != k:
                p = p * ((x - Lx[j]) / (Lx[k] - Lx[j]))
        y  = p * Ly[k]
    return y

poly1=simplify(Lagrange(P_Maz,H_Maz))
poly2=simplify(Lagrange(P_Lig,H_Lig))

print(Lagrange(P_Maz, H_Maz)) #Morfh Klasmatwn
print(poly1) #Telikh eksiswsh
print(lagrange(P_Maz,H_Maz)) #Telikh eksiswsh me built in method

print(Lagrange(P_Lig, H_Lig)) #Morfh Klasmatwn
print(poly2) #Telikh eksiswsh
print(lagrange(P_Lig,H_Lig)) #Telikh eksiswsh me built in method

plot(P_Maz,poly1(P_Maz))
grid()
show()

CodePudding user response:

With simplify, you get an expression, but then you need to evaluate that expression for all the desired values.

You can do that through lambdify:

from sympy import lambdify

f = lambdify(x, simplify(Lagrange(P_Maz,H_Maz)), "numpy") 
# above, just copied your simplify call with your variables and used in the lambdify

plot(P_Maz, f(P_Maz)) # use the created lambdify function, f, not the unevaluated expression

Mind the warning in the documentation (docs): "lambdify uses eval. Don’t use it on unsanitized input."

  • Related