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.
Related
Hello I'm trying to integrate a function stored in a variable
from scipy.integrate import quad
fun= x+1
result= quad(fun,2,0)
I know the fun should be instead a int but do you know how I can integrate a function stored this way? I tried to use lambda x:... but I want to use 'fun' and not lambda x :x+1
As part of a wider plotting program I have a script where there is a function f defined as a lambda expression, and I need to find its derivative. My code for testing the script is:
import math
import sympy as sym
f = lambda x : math.sin(x)
sx = sym.symbols('x')
sf = sym.diff(f(sx), sx)
print(sf)
While this works fine when f is defined without using any outside methods, the above throws TypeError: can't convert expression to float because the math module's methods don't support the symbolic representations used by Sympy. However, while this works when f instead uses sym.sin, because of how the aforementioned program is structured the definition of f cannot be changed. Is there a way to symbolically interpret the math module's methods?
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 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
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.