How to calculate norm of a vector using Sympy - python

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)

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.

How to solve this homogenious first-order differential equation in python? x*∂y/∂x=y+2x^3*sin^2(y/x)

x∂y/∂x=y+2x^3sin^2(y/x)
This is what I tried:
from math import *
from sympy import *
x = symbols('x')
y = symbols('y', cls=Function)
eq = Eq(Derivative(y(x),x), 2*x**2 * sin(y(x)/x)**(2) + y(x)/x)
display(eq)
an_sol = dsolve(eq, y(x))
display(an_sol)
But it shows problem:
NotImplementedError: The given ODE -2*x**2*sin(y(x)/x)**2 + Derivative(y(x), x) - y(x)/x cannot be solved by the lie group method

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 check if an expression is a sympy vector

How can I tell if a sympy expression is a vector? See the following example:
from sympy import *
from sympy.vector import *
N = CoordSys3D('N')
x = symbols('x')
v = x * N.i + x**2 * N.j + x**3 * N.k
type(v)
# sympy.vector.vector.VectorAdd
vf=factor(v)
vfs = vf.as_ordered_factors()
vfs
#[x, N.i + N.j*x + N.k*x**2]
type(vfs[1])
# sympy.core.add.Add
After v was factored, none of its factors have a sympy.vector... type. How can I tell which one of its factors is a vector? Is there a test for that?
SymPy has a variety of ways to search/parse expressions. Something that may work for you is the as_independent method:
>>> vf.as_independent(Vector)
(x, N.i + N.j*x + N.k*x**2)
You Vector-dependent part of vf will be the rightmost element.

Multivariable multiplication in 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')

Categories