I'd like to consecutively plot the zeros of several Jacobi polynomials. The parameters and degree of the Jacobi polynomials depend on a certain size variable n. I want to compute the roots of each polynomial by first extracting the coefficients of the polynomial into an array. However, this cannot be done with the coeffs() command since the Jacobi polynomial is of class sympy.core.add.Add, which does not have coeffs() as an attribute. Any suggestions on how to overcome this problem?
import matplotlib.pyplot as plt
init_printing()
x = Symbol("x")
def show_roots(n,a,b,c):
for k in range (1,n+1):
p = jacobi(a*k,-(a+b)*k,(b+c)*k,x)
coeff = p.coeffs(x)
roots = numpy.roots(coeff)
plt.plot(roots)
plt.show()
plt.pause(3)
The error I am shown when I try out show_roots with specific values:
AttributeError: 'Add' object has no attribute 'coeffs'
You need to convert Add to Poly first then call coeffs() on the result.
import matplotlib.pyplot as plt
import sympy
import numpy
x = sympy.symbols('x')
def show_roots(n,a,b,c):
for k in range (1,n+1):
p = sympy.jacobi(a*k,-(a+b)*k,(b+c)*k,x)
coeff = sympy.poly(p).coeffs()
roots = numpy.roots(coeff)
print(roots)
show_roots(3,1,2,3)
gives
[2.]
[2.+0.65465367j 2.-0.65465367j]
[2.24801968+0.j 1.87599016+0.92968658j 1.87599016-0.92968658j]
You can now do the plotting stuff.
Related
Click here to see traceback
I have the following question:
Write a Python program to generate data that uses the sum of a random variable (which has a Gaussian distribution) and a 4th-degree polynomial equation (3x4+x3+3x2+4x+5). Using least squares polynomial fit, curve the generated data using a model until your model can accurately predict all values
with the following start on the question:
import random
import numpy as np
import matplotlib.pyplot as plt
def mainFunc():
poly_coeff=[3,1,3,4,5]
poly=np.poly1d(poly_coeff)
print(poly)
y = poly(random.randint(0,10)) + min(10,max(0,random.gauss(2,3)))
x=np.arange(-10,10)
curvefit=np.polyfit(x,y,4)
y_new=np.polyfit(curvefit,x)
plt.plot(x,y, '-or')
plt.plot(x,y_new, '-b')
plt.show()
mainFunc()
Can anyone help with the array error that is being generated?
I have to program the Jacobi, Gauss Seidel and SOR methods to resolve Ax=b. We use a decomposition A=M-N.
For the Jacobi method, for example, we use M=diag(A) and N=M-A.
I programmed a function
jacobi(A,b,Imax,err,x0)
with the matrix A, the column vector b, a maximum number of iterations Imax, a tolerance err, for the Jacobi method. I used a "stop test" where is the "residual" at the step k.
Here is my code :
import numpy as np
import scipy.linalg as la
def jacobi(A,b,Imax,eps,x0):
M=np.diag(np.diag(A))
N=M-A
r=np.dot(A,x0)-b
x=x0
i=0
err=1+eps
res=[]
while ((i<Imax) and ((la.norm(r))>=eps)):
x=np.dot(np.dot((la.inv(M)),N),x)+np.dot((la.inv(M)),b)
r=np.dot(A,x)-b
err = la.norm(r,2)
res.append(err)
i=i+1
return (x,i,res)
and the test :
A=np.array([[2,0,0],[4,5.4,0],[7,8,9]])
x0=np.array([[1],[1],[1]])
b=np.array([[20],[8],[7]])
print(jacobi(A,b,1000,10**(-3),x0))
Now, I have to represent on a graph (in logarithmic scale for ordinates) the values in function of n.
I just would like to know how to represent a graph in logarithmic scal ? I'm beginner in Python and I don't know how to represent a graph... I tried to be clear, sorry for my bad English...
here is a log plot for some dummy values
import matplotlib.pyplot as plt
import numpy as np
j = np.power(10,range(10)) # <--- here use your computed values instead
plt.plot(j)
plt.yscale('log')
plt.show()
If you want log-log set the xscale as well.
I have a script drawing a set of (x,y) curves at various z.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,1,100)
z = np.linspace(0,30,30)
def y(z, x):
return z**(1-x)
for i in z:
plt.plot(x, y(i,x))
How can I draw dy/dx at x=0 versus z?
plt.plot(z, dy/dx at x=0)
In fact, I need to calculate the slope at the x=0 boundary for each (x,y) curve (shown below), then plot the slopes against z.
You must use the derivative function:
scipy.misc.derivative(func, x0, dx=1.0, n=1, args=(), order=3)
Find the n-th derivative of a function at a point.
Given a function, use a central difference formula with spacing dx to
compute the n-th derivative at x0.
Parameters:
func : function Input function.
x0 : float The point at which n-th derivative is found.
dx : float, optional Spacing.
n : int,optional Order of the derivative. Default is 1.
args : tuple, optional
Arguments order : int, optional Number of points to use, must be odd.
In your case:
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import derivative
x = np.linspace(0,1,100)
z = np.linspace(0,30,30)
x0 = 0
def y(z, x):
return z**(1-x)
dydx = [derivative(lambda x : y(zi, x) , x0) for zi in z]
plt.plot(z, dydx)
plt.show()
Screenshot:
You mixed up the variables in the description. I assume you have a function y in variables (x,z). So you need to calculate dy/dx and dy/dz.
You have a few options to calculate the derivative, including symbolic calcultation (using SymPY) or just straightfoward finite differences calculation (prone to numerical errors) See this: How do I compute derivative using Numpy?.
But, you cannot plot this derivative since you are calculating it at a point (x=0,z=0), therefore the result is a float number, and not a function. To make the plot you want you need to calculate the general symbolic derivative (dydx) and make the plot you suggested. To get the result at point (0,0), just dydx(0,0).
Btw, dydz = (1-x)z**(-x) and dydx = -ln(z)*z**(1-x) using this.
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import LSQUnivariateSpline
x = np.linspace(-3,3,7)
y = np.sin(x)
t = [-1,1]
LSQ_USpline = LSQUnivariateSpline(x, y, t, k = 3)
print(LSQ_USpline.get_coeffs())
As far I understand I am getting 3 polynomials pieced back together. The output of LSQ_USpline.get_coeffs() is
[-0.14112001 -0.90624802 -1.47578155 1.47578155 0.90624802 0.14112001]
I thought that first two coefficients are related to the first polynomial, in particular a_0 -> -0.14112001 and a_1 -> -0.90624802, where a_0 is the coefficient of x^3. After plotting it I realized that it is not true.
Could somebody help me to understand what how to read output of LSQ_USpline.get_coeffs()?
Update: Overall what do coefficients of spline mean? I thought they are coefficients of polynomials of the spline.
Update: After differentiating and checking values at zero get_coeffs() is definitely not coefficients of polynomials or there is a bug in this function.
I'm trying to solve the equation y'' + (epsilon-x^2)y = 0 numerically using odeint. I know the solutions (the wavefunctions of a QHO), but the output from odeint has no apparent relation to it. I can solve ODEs with constant coefficients just fine, but as soon as I move to variable ones, I can't solve any of the ones I tried. Here's my code:
#!/usr/bin/python2
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as spi
x = np.linspace(-5,5,1e4)
n = 0
epsilon = 2*n+1
def D(Y,x):
return np.array([Y[1], (epsilon-x**2)*Y[0]])
Y0 = [0,1]
Y = spi.odeint(D,Y0,x)
# Y is an array with the first column being y(x) and the second y'(x) for all x
plt.plot(x,Y[:,0],label='num')
#plt.plot(x,Y[:,1],label='numderiv')
plt.legend()
plt.show()
And the plot:
[not enough rep:] https://drive.google.com/file/d/0B6840LH2NhNpdUVucUxzUGFpZUk/edit?usp=sharing
Look here for plots of solution: http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/hosc5.html
It looks like your equation is not correctly interpreted. You have a differential equation y'' + (epsilon-x^2)y = 0, but you forget a minus sign in your vector form. In particular it should be
y[0]' = y[1]
y[1]' = -(epsilon-x^2)y[0]
So (adding the minus sign in front of the epsilon term
def D(Y,x):
return np.array([Y[1], -(epsilon-x**2)*Y[0]])
In fact the plot you have is consistent with the DE y'' + (epsilon-x^2)y = 0. Check it out: Wolphram Alpha