Rei
Rei

Reputation: 3

Multiple errors attempting to solve a function with fsolve and sym solve in python

I am trying to solve the function below. I've attempted to use a symbolic solver and fsolve. Both are causing me trouble. First time posting, I apologize in advance if I'm missing something in my question.

Does anyone have a suggestion on how to solve this? I am solving for y, everything else is a known variable.

cos(y) + ((xi - tdd) / y) * sin(y)) - exp(xi - tii)

I attempted this in python using two ways, both did not work. The first is:

import numpy as np
from scipy.optimize import fsolve
import sympy as sym
from sympy import *

def fi(y):
    return ((cos(y) + ((xi - tdd) / y) * sin(y)) - exp(xi - tii))
y = fsolve(fi,0.01)

With this code I get this error:

AttributeError: 'ImmutableDenseNDimArray' object has no attribute 'could_extract_minus_sign'

I also tried this:

y = symbols('y')
init_printing(use_unicode=True)
yi = solve(cos(y) + ((xi - tdd) / y) * sin(y)) - exp(xi - tii))

And got this error:

NotImplementedError: multiple generators [y, tan(y/2)] No algorithms are implemented to solve equation y*(10000000000000000*(-tan(y/2)**2 + 1)/(tan(y/2)**2 + 1) - 9849605264665270) - 300789470669454*tan(y/2)/(tan(y/2)**2 + 1)

This is how I solved it in Matlab (i and j because I have x values in a matrix that need to be solve):

fi = @(y,x) (cos(y) + (((x-tdd)/y)*sin (y))) - exp((x - tii));
yi(i) = fzero(@(y) fi(y,xi(i,j)),.01);

Upvotes: 0

Views: 885

Answers (1)

Saviour
Saviour

Reputation: 322

As I already addressed in a comment, the solve function isn't geared to solve such equations. More information can be found here.

Regarding fsolve, it appears that the problem is caused because you are using the sin, cos and exp functions from sympy. If you replace them with the functions from the math module the code should work.

Specifically, your code should look like this:

import math
from scipy.optimize import fsolve

def fi(y):
    return ((math.cos(y) + ((xi - tdd) / y) * math.sin(y)) - math.exp(xi - tii))

y = fsolve(fi, 0.01)

Upvotes: 1

Related Questions