Multivariable multiplication in python - python

No idea how to multiply two polynomials of different variable. Below is my code and running it on IPython.
from sympy import *
from numpy import *
m1 = poly1d([1,0,0,1], variable = 'x')
m2 = poly1d([1,0], variable = 'y')
p=m1*m2
print(p)
Expected result is a polynomial with variable x and y but below is my result.
4
1 x + 1 x

now you're using numpy.poly1d, which doesn't seem to take the variable= into account. If you want to do it symbolicallly, you can use sympy.Poly
from sympy import Poly
from sympy.abc import x, y
m1 = Poly((1, 0, 0, 1), x)
m2 = Poly((1,0), y)
m1, m2
(Poly(x**3 + 1, x, domain='ZZ'), Poly(y, y, domain='ZZ'))
m1 * m2
Poly(x**3*y + y, x, y, domain='ZZ')

Related

Code giving NameError: name 'x' is not defined

I am new to Python, and I am trying to make a numerical analysis model of differential equations.
import sympy as sympy
def picard_solver(y_0, x_0, rhs_expression, iteration_count:int = 5):
x, phi = sympy.symbols("x phi")
phi = x_0
for i in range(iteration_count + 1):
phi = y_0 + sympy.integrate(rhs_expression(x, phi), (x, x_0, x))
return phi
import numpy
import plotly.graph_objects as go
y_set = [picard_solver(1, 0, lambda x, y: x * y, i) for i in range(1, 6)]
x_grid = numpy.linspace(-2, 2, 1000)
y_picard = list()
for y in y_set:
y_picard.append(numpy.array([float(y.evalf(subs={x: x_i})) for x_i in x_grid]))
y_exact = numpy.exp((x_grid) * (x_grid) / 2)
fig = go.Figure()
for i, y_order in enumerate(y_picard):
fig.add_trace(go.Scatter(x=x_grid, y=y_order, name=f"Picard Order {i + 1}"))
# fig.add_trace(go.Scatter(x=x_grid, y=y_picard, name="Picard Solution"))
fig.add_trace(go.Scatter(x=x_grid, y=y_exact, name="Exact Solution"))
fig.show()
fig.write_html("picard_vs_exact.html")
But when I try to run it, I get NameError: name 'x' is not defined error, can someone help me?
I want a graph to be shown.
I think that you need to pass a string in the y.evalf(subs={'x': x_i}) part of your code.

Find maxima for a negative parabolic equation

I have the following negative quadratic equation
-0.03402645959398278x^{2}+156.003469x-178794.025
I want to know if there is a straight way (using numpy/scipy libraries or any other) to get the value of x when the slope of the derivative is zero (the maxima). I'm aware I could:
change the sign of the equation and apply the scipy.optimize.minima method or
using the derivative of the equation so I can get the value when the slope is zero
For instance:
from scipy.optimize import minimize
quad_eq = np.poly1d([-0.03402645959398278, 156.003469, -178794.025])
############SCIPY####################
neg_quad_eq = np.poly1d(np.negative(quad_eq))
fit = minimize(neg_quad_eq, x0=15)
slope_zero_neg = fit.x[0]
maxima = np.polyval(quad_eq, slope_zero_neg)
print(maxima)
##################numpy######################
import numpy as np
first_dev = np.polyder(quad_eq)
slope_zero = first_dev.r
maxima = np.polyval(quad_eq, slope_zero)
print(maxima)
Is there any straight way to get the same result?
print(maxima)
You don't need all that code... The first derivative of a x^2 + b x + c is 2a x + b, so solving 2a x + b = 0 for x yields x = -b / (2a) that is actually the maximum you are searching for
import numpy as np
import matplotlib.pyplot as plt
def func(x, a=-0.03402645959398278, b=156.003469, c=-178794.025):
result = a * x**2 + b * x + c
return result
def func_max(a=-0.03402645959398278, b=156.003469, c=-178794.025):
maximum_x = -b / (2 * a)
maximum_y = a * maximum_x**2 + b * maximum_x + c
return maximum_x, maximum_y
x = np.linspace(-50000, 50000, 100)
y = func(x)
mx, my = func_max()
print('maximum:', mx, my)
maximum: 2292.384674478263 15.955750522436574
and verify
plt.plot(x, y)
plt.axvline(mx, color='r')
plt.axhline(my, color='r')

How to substitute variable in multiple equations in Sympy

for example, if I want to use solve a set of linear equations
eq1: x + y + 8z = 2
eq2: 2x + 6y + z = 5
suppose I already know the value of z, is there any way I can subsitute the z in eq1 and eq2 in one operation such as
linear_equations([eq1, eq2]).subs({z: 100})
You can use the Sympy library to achieve what exactly you are looking to solve.
Below is the code which will perform the substitution of the Z value and then solve the linear equation to find the values of x & Y values
from sympy import symbols
from sympy.solvers import solve
x,y,z = symbols('x y z')
expression1 = x + y + 8*z - 2
expression2 = 2*x + 6*y + z - 5
expression1 = expression1.subs(z,100)
expression2 = expression2.subs(z,100)
solution = solve([expression1, expression2], [x, y])
print(solution)

How to calculate norm of a vector using Sympy

I need to calculate the norm of a vector using sympy and Symbol from sympy. An extract of the code is below:
from sympy import *
x = Symbol('x')
sb = [2,1]
func = sympy.exp(-(sympy.sqrt((x.norm() + (x-sb).norm())**2 - sb**2)/(2)))
func_prime = func.diff(x)
ff = lambdify(x, func_prime, 'numpy')
f = -1*ff(np.array(r))
The above implementation gives me the error: AttributeError: 'Symbol' object has no attribute 'norm'.
If I use func = V0 * sympy.exp(-(sympy.sqrt((sympy.sqrt(sum(x**2)) + sympy.sqrt(sum((x-sb*e)**2)))**2 - sb**2)/(2*sig))) I get the following error: TypeError: 'Pow' object is not iterable.
numpy.linalg.norm() is not accepted by sympy.
How can I find the norm of a vector in this situation?
Thanks
Sympy has a vector module you can use.
from sympy.vector import CoordSys3D
C = CoordSys3D('C')
v = 3*C.i + 4*C.j + 5*C.k
v.dot(v)
Output: 50
You can also use it with symbols:
from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
v = x*C.i + y*C.j + z*C.k
sympy.sqrt(v.dot(v))
Output: sqrt(x**2 + y**2 + z**2)
Hello :) i suggest you the following:
import sympy as sp
import sympy.physics.vector as spv
M = spv.ReferenceFrame("M")
vector=V1*M.x+V2*M.y+V3*M.z
Where M.x, M.y, M.z are the unitary vectors i, j, k in physics. As we know the norm is the square root of the dot product of the vector with itself, so
norm=sp.sqrt(spv.dot(vector, vector))
print(norm)
If you want to print the result in LaTeX format
print(sp.latex(norm))
If you want to simplify the expresion,
print(norm.simplify())
x, y, z = symbols('x y z')
vec = Matrix([x, y, z])
vec_norm = sqrt(sum(sympy.matrices.dense.matrix_multiply_elementwise(vec, vec)))
How about this?
from sympy import *
x = Symbol('x')
y = Symbol('y')
a = Matrix([x,y])
anorm = sqrt(a.T # a)

How to find the difference of x -y using sympy

As you see in the code, I want to find the difference of x-y using the resulting R of solve. But, the code keeps returning x-y as value. Please help me. I am a 10 year old kid that just started coding.
import sympy as sp
x, y = sp.symbols ('x, y')
eq1 = sp.Eq(7 * x, 12 * y)
eq2 = sp.Eq(x+y, 9500)
R = sp.solve ((eq1, eq2), (x, y))
print (x-y)
The result R of sp.solve is a Python dictionary with values for x and for y:
import sympy as sp
x, y = sp.symbols('x, y')
eq1 = sp.Eq(7 * x, 12 * y)
eq2 = sp.Eq(x + y, 9500)
R = sp.solve((eq1, eq2), (x, y))
Result: {x: 6000, y: 3500}
To apply the resulting dictionary to an expression, use subs(R):
print((x - y).subs(R))
Result: 2500

Categories