简体   繁体   中英

How to numerically solve an equation (translate code from Matlab to Python)

I can't find any equivalent of the Matlab function vpasolve , which numerically solves an equation. The following is my attempt

Python:

alfa = sympy.Symbol('alfa')
y = np.linspace(0, 100, 6)
angleR = np.zeros((1, np.size(y)))

i = 1

for x in range(0, 100, 20):
    p = x/100
    angleR[0, i] = np.rad2deg((sympy.solve(2*np.pi*(1-p) == np.sin(2*alfa), alfa)).astype(float))
    i = i + 1
print(angleR)

Which produces the following error

TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable sin method

Original Matlab code:

syms alfa
y = 0:20:100;
angleR = zeros(1, length(y));
i = 1;
for j = 0:20:100
  p = j/100;
  angleR(i) = rad2deg(double(vpasolve(2*pi*(1-p) == 2*alfa - sin(2*alfa), alfa)));
  i = i+1
end

There are a few issues:

  • You're mixing sympy and numpy. Numpy deals with numerical inputs, so np.sin tries to evaluate 2*alfa , which is a Mul object and fails. For a symbolic expression you'd need to use sympy.sin instad.
  • The equation syntax in sympy is sympy.Eq(lhs, rhs) (and you even got the expression wrong).
  • To solve an equation numerically use sympy.nsolve , with the syntax sympy.nsolve(lhs - rhs, variable, initial_guess) .

All in all, the following code produces the same result as Matlab. Some minor liberties were taking, ie putting the result in a 1D array instead of a "column vector", which is actually a 2D array. But the spirit of the solution is there and you can modify the result format easily.

import numpy as np
import sympy as sym

alfa = sym.Symbol('alfa')
p_values = np.arange(0, 101, 20) / 100
angleR = [
    np.rad2deg(float(sym.nsolve(2*np.pi*(1-p) - 2*alfa + sym.sin(2*alfa), alfa, 0)))
    for p in p_values
]
angleR = np.array(angleR)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM