I am using Python to solve an equation. I added the 'Bessel function' in scipy.special, It was working. Now I want to find a variable using Bessel function. For example, I added the order(1) and value(0.44005058574) in Python, but it is not working. (in order to find the variable, I also used solver)
How I can solve the problem?
import numpy as np
import scipy.special as sc
import math
from sympy import Symbol
from sympy.solvers import solve
x=Symbol('x')
y=sc.jn(1,x)-0.44005058574
print(solve(x))
As the output is hinting, the function scipy.special.jn does not know how to handle the object x from simpy. Instead, you should use a numerical approach
>>> from scipy import optimize
>>> f = lambda x: sc.jn(1, x) - 0.44005058574
>>> root = optimize.newton(f, 1.0)
>>> print(root)
0.9999999999848267
Related
I use the following example to try to solve the inequality containing tanh, but it produces the error
TypeError: Equation should be a polynomial with Rational coefficients
Anyone knows how to solve it ?
from sympy import Symbol, S
from sympy.solvers.solveset import solveset
x=Symbol('x')
v=0.05*x-8.5
solveset((1-(2*exp(-v))/(exp(v)+exp(-v)))>0, x, S.Reals)
You need to use exp from SymPy:
from sympy import Symbol, S
from sympy.functions import exp
from sympy.solvers.solveset import solveset
x = Symbol('x')
v = 0.05*x-8.5
solveset((1-(2*exp(-v))/(exp(v)+exp(-v)))>0, x, S.Reals)
which yields
Interval.open(170.000000000000, oo)
Having updated the sympy version to 1.9, the code finally works well for me.
Btw, in my case, in order to update the sympy, I should also update python to a newer version (currently 3.9.7) from my older version (3.7.1) since each python version seems to correspond to (a) certain sympy version(s).
I am trying to solve an equation for r when given values for x and y. to do this I am using the solve ability of sympy. the code that I have is
import numpy as np
import matplotlib.pyplot as plt
from sympy import solve
from sympy import Symbol
from sympy import acos,sin
x=2
y=-2
r=Symbol("r",real=True)
solve(r(acos(1.0-(y/r)))-sin(acos(1.0-(y/r)))-x)
when I run the code it gives me the error
'Symbol' object is not callable
line 10, in <module>
solve(r(acos(1.0-(y/r)))-sin(acos(1.0-(y/r)))-x)
the reason I import numpy and matplotlib is that I will use them later in my code. Thanks for any help.
The error directs you toward what to look for: a Symbol that is being called. In Python syntax this is a Symbol followed by pair of parentheses with one or more arguments between them. You probably intended to multiply by r in the first argument of the expression:
>>> solve(r(acos(1.0-(y/r)))...
^__make that r*acos(1.0-(y/r))...
An editor that highlights matching parentheses (like the online editor of Python code at repl.it) can be helpful in these circumstances. Parentheses are either grouping or, when following a Python name, acting as the delimiters for the arguments being passed to a function.
In Pyomo I want to solve the following minimization problem, which matches the playback rate and timing of two audio files:
import pyomo
from pyomo.environ import *
from pyomo.opt import SolverFactory
import soundfile as sf
import math
import numpy
#Create Model:
model = ConcreteModel()
#Declare Variables:
model.P = Var(initialize = 1, within=PositiveReals, bounds = (0.5,2))
model.T = Var(initialize = 0, within=Reals, bounds = (-500,500))
#Objective function:
def shift(data,rate,t,point):
Y=numpy.zeros(len(data))
for i in range(len(data)):
for j in range(point):
if math.floor(i*rate+t-j+point/2)>=0 and math.floor(i*rate+t-j+point/2)<=len(data)-1:
Y[i]+=data[math.floor(i*rate+t-j+point/2)]*numpy.sinc((math.floor(i*rate+t)-i*rate-t)-(j-point/2))
return Y
def obj_fun(model):
#Read data from audiofile:
Audio1, samplerate = sf.read('C:/Audio1.wav')
Audio2, samplerate = sf.read('C:/Audio2.wav')
Audio1=Audio1[:,0]
Audio2=Audio2[:,0]
Audio2= numpy.pad(Audio2,(0,len(Audio1)-len(Audio2)),'constant', constant_values=(0, 0))
return -1*numpy.sum(shift(Audio2,model.P,model.T,4)*Audio1)
#Create obj function:
model.obj = Objective(rule=obj_fun, sense=1)
The problem is the following error:
TypeError: Implicit conversion of Pyomo NumericValue type `<class 'pyomo.core.base.expr_coopr3._SumExpression'>' to a float is
disabled. This error is often the result of using Pyomo components as
arguments to one of the Python built-in math module functions when
defining expressions. Avoid this error by using Pyomo-provided math
functions.
The solver can't function unless numpy's/math's sinc and floor functions are changed. However, in Pyomo's documentation there is no reference to Pyomo-provided functions. What do I change the standard sinc/floor functions with in order to get the model object created without errors?
Also I am wondering whether there is a smarter way to read the data into the model. As of now, it's unnecessarily read on every pass of the objective function.
Pyomo provided intrinsic functions (sin, log, etc.) are automatically imported with the line from pyomo.environ import *. The problem is that you are importing math after that line which overwrites Pyomo's intrinsic functions with the ones from the math library. The solution is to remove the math import statement entirely or to move the math import statement above the pyomo import statement.
This question already has an answer here:
Is there a way to bypass the namespace/module name in Python?
(1 answer)
Closed last month.
I am using Canopy with the Jupyter notebook. I was wondering if there was a way to use function from a module without having to call the module. For example if I have
import numpy as np
print np.sin(2)
I would want to be able to just type
print sin(2)
The first thing that comes to mind is to add the numpy functions into whatever function library that Python is using. But I was wondering if this is feasible and, if so, how I could go about doing it. Note that I want to import all functions, not just a select few.
You can import specific objects from a module. Try:
from numpy import sin
print sin(2)
To import all objects from a module into the global namespace you can use import *.
from numpy import *
print sin(2)
But this is not recommended because you can easily end up with name clashes, e.g. if two modules define a function named sin which version of sin should be called?
>>> import math
>>> import numpy
>>> math.sin
<built-in function sin>
>>> numpy.sin
<ufunc 'sin'>
>>> from math import *
>>> sin
<built-in function sin>
>>> from numpy import *
>>> sin
<ufunc 'sin'>
You can see here that the second import from numpy replaced sin in the global namespace.
For this reason it is best to import the specific objects that you need if there are only a few, otherwise just import the module and use the module name as a prefix (as per your first example). In my example if you wanted to use both math.sin and nump.sin you would either need to import the modules only and prefix using the module name, or import the functions and rename them like this:
from numpy import sin as np_sin
from math import sin
from numpy import sin
print sin(2)
https://docs.python.org/2/tutorial/modules.html read this in details
import numpy as np
import sympy as sym
from numpy import sin
from sympy import symbols, diff
func = lambda x: sin(x)
x = symbols('x')
print diff(func(x),x)
This works if I replace my function with a polynomial, or if I place the trig function directly into the diff operator. But in this format I get AttributeError: sin.
Basically I think python can't recognize func as just being a trig function which it knows how to symbolically integrate. I could just have sympy import sin and then things would work, but then I'm stuck with func referencing sin in the sympy namespace and there are future things I want to do with func which require that it be defined using sin in the numpy namespace.
You should build your expression up symbolically using SymPy functions, and then use lambdify to convert them into things that can be evaluated with NumPy.
This simply isn't how you use sympy. You can't use normal functions in conjunction with numpy--you need to build symbolic expressions using the stuff it provides.
To write code to get the derivative of sin(x), you would do
import sympy as sym
from sympy import sin, symbols, diff
x = symbols('x')
print diff(sin(x), x)
If you have some other particular case you're having trouble with, you'll have to show it. You can't mix sympy with non-sympy stuff in this way, so there isn't some general feedback that can be provided.