我发现自己想要使用作为mpmath包的一部分提供的近似值,但却对它们应该做的事情感到困惑:
http://docs.sympy.org/dev/modules/mpmath/calculus/approximation.html
表情符号表达与sympy.mpmath表达之间究竟有什么区别?
如果我想要一个符号表达式的泰勒近似而不了解mpmath包正在做什么,我可以执行以下操作:
#Imports
import sympy
import sympy.parsing
import sympy.parsing.sympy_parser
import Library_TaylorApproximation
#Create a sympy expression to approximate
ExampleStringExpression = 'sin(x)'
ExampleSympyExpression = sympy.parsing.sympy_parser.parse_expr(ExampleStringExpression)
#Create a taylor expantion sympy expression around the point x=0
SympyTaylorApproximation = sympy.series(
ExampleSympyExpression,
sympy.Symbol('x'),
1,
4,
).removeO()
#Cast the sympy expressions to python functions which can be evaluated:
VariableNames = [str(var) for var in SympyTaylorApproximation.free_symbols]
PythonFunctionOriginal = sympy.lambdify(VariableNames, ExampleSympyExpression)
PythonFunctionApproximation = sympy.lambdify(VariableNames, SympyTaylorApproximation)
#Evaluate the approximation and the original at a point:
print PythonFunctionOriginal(2)
print PythonFunctionApproximation(2)
#>>> 0.909297426826
#>>> 0.870987413961
但是,如果我尝试使用基于文档的mpmath做同样的事情:
TaylorCoefficients = sympy.mpmath.taylor(ExampleSympyExpression, 1, 4 )
print 'TaylorCoefficients', TaylorCoefficients
#>>> TypeError: 'sin' object is not callable
我可以尝试在那里填充python函数(可调用):
TaylorCoefficients = sympy.mpmath.taylor(PythonFunctionOriginal, 1, 4 )
print 'TaylorCoefficients', TaylorCoefficients
#>>> TaylorCoefficients [mpf('0.8414709848078965'), mpf('0.0'), mpf('0.0'), mpf('0.0'), mpf('-8.3694689805155739e+57')]
但是上面没有任何意义,因为我知道衍生物不能被用于python函数。
我可以调用mpmath函数sin
:
TaylorCoefficients = sympy.mpmath.taylor(sympy.mpmath.sin, 1, 4 )
print 'TaylorCoefficients', TaylorCoefficients
#>>> TaylorCoefficients [mpf('0.8414709848078965'), mpf('0.54030230586813977'), mpf('-0.42073549240394825'), mpf('-0.090050384311356632'), mpf('0.035061291033662352')]
但是我不能按照我想要的方式对它进行操作 - >如果我想要
SinTimesCos = sympy.mpmath.sin*sympy.mpmath.cos
TaylorCoefficients = sympy.mpmath.taylor(SinTimesCos, 1, 4 )
print 'TaylorCoefficients', TaylorCoefficients
#>>> TypeError: unsupported operand type(s) for *: 'function' and 'function'
究竟什么是mpmath函数?
它不是一个表达式,它也不是一个python函数。如何对任意表达式进行操作?
似乎我无法在文档中对任意同情表达式进行近似。 http://docs.sympy.org/dev/modules/mpmath/calculus/approximation.html
如何进行任意近似(Pade / Cheby Chev / Fourier) 任意的同情表达?
编辑:
所以我正在寻找的一个例子是以下近似值:
#Start with a sympy expression of (a, b, x)
expressionString = 'cos(a*x)*sin(b*x)*(x**2)'
expressionSympy = sympy.parsing.sympy_parser.parse_expr(expressionString)
#Do not want to decide on value of `a or b` in advance.
#Do want approximation with respect to x:
wantedSympyExpression = SympyChebyChev( expressionSympy, sympy.Symbol('x') )
结果可以是a
和b
函数的系数表达式列表:
wantedSympyExpressionCoefficients = [ Coef0Expression(a,b), Coef1Expression(a,b), ... , CoefNExpression(a,b)]
或者结果可能是整个症状表达本身(它本身是a
,b
的函数):
wantedSympyExpression = Coef0Expression(a,b) + Coef1Expression(a,b) *(x**2) + ... + CoefNExpression(a,b) (x**N)
请注意,在执行近似值之前未选择a
和b
。
答案 0 :(得分:1)
mpmath函数是普通的Python函数。他们只是在任意精度算术中进行数学运算。
但是上面没有任何意义,因为我知道衍生物不能用于python函数。
您无法使用符号衍生,但您可以通过多次评估函数并使用数值微分技术来计算导数的近似值。这就是sympy.mpmath.taylor
的作用。引用文档:
使用高阶数值微分来计算系数。该函数必须能够评估为任意精度。
答案 1 :(得分:1)
如果您有一个SymPy表达式并想要将其评估为任意精度,请使用evalf
,例如
sympy.sin(1).evalf(100)
在评估之前,您可以使用sin(x).evalf(100, subs={x:1})
将x
替换为1
。 evalf
使用mpmath,因此这将给你与mpmath相同的结果,但不必直接使用mpmath。
答案 2 :(得分:0)
编辑:重读我的回答 - >我以为我会填写一些缺失的部分作为服务某人实际上有一天使用它。下面我标注了我如何命名我的库,以及需要哪些导入。我现在没有时间成为真正的同情者,但觉得这个功能肯定会被其他数学/物理学教授/学生使用。
请注意,由于空间原因,省略了以下两个库,我将在以后的某个日期将链接发送到我的仓库。
import Library_SympyExpressionToPythonFunction
在sympy表达式中创建一个python可调用函数对象,其中包含自由变量的args(数字和名称)。
import Library_SympyExpressionToStringExpression
字面意思就是str(SympyExpression)
#-------------------------------------------------------------------------------
Library_GenerateChebyShevPolynomial :::
#-------------------------------------------------------------------------------
import pprint
import Library_SympyExpressionToPythonFunction
import Library_SympyExpressionToStringExpression
import sympy
import sympy.core
def Main(
ApproximationSymbol = sympy.Symbol('x'),
ResultType = 'sympy',
Kind= None,
Order= None,
ReturnAll = False,
CheckArguments = True,
PrintExtra = False,
):
Result = None
if (CheckArguments):
ArgumentErrorMessage = ""
if (len(ArgumentErrorMessage) > 0 ):
if(PrintExtra):
print "ArgumentErrorMessage:\n", ArgumentErrorMessage
raise Exception(ArgumentErrorMessage)
ChebyChevPolynomials = []
ChebyChevPolynomials.append(sympy.sympify(1.))
ChebyChevPolynomials.append(ApproximationSymbol)
#Generate the polynomial with sympy:
for Term in range(Order + 1)[2:]:
Tn = ChebyChevPolynomials[Term - 1]
Tnminus1 = ChebyChevPolynomials[Term - 2]
Tnplus1 = 2*ApproximationSymbol*Tn - Tnminus1
ChebyChevPolynomials.append(Tnplus1.simplify().expand().trigsimp())
if(PrintExtra): print 'ChebyChevPolynomials'
if(PrintExtra): pprint.pprint(ChebyChevPolynomials)
if (ReturnAll):
Result = []
for SympyChebyChevPolynomial in ChebyChevPolynomials:
if (ResultType == 'python'):
Result.append(Library_SympyExpressionToPythonFunction.Main(SympyChebyChevPolynomial))
elif (ResultType == 'string'):
Result.append(Library_SympyExpressionToStringExpression.Main(SympyChebyChevPolynomial))
else:
Result.append(SympyChebyChevPolynomial)
else:
SympyExpression = ChebyChevPolynomials[Order] #the last one
#If the result type is something other than sympy, we can cast it into that type here:
if (ResultType == 'python'):
Result = Library_SympyExpressionToPythonFunction.Main(SympyExpression)
elif (ResultType == 'string'):
Result = Library_SympyExpressionToStringExpression.Main(SympyExpression)
else:
Result = SympyExpression
return Result
#-------------------------------------------------------------------------------
Library_SympyChebyShevApproximationOneDimension
#-------------------------------------------------------------------------------
import numpy
import sympy
import sympy.mpmath
import pprint
import Library_SympyExpressionToPythonFunction
import Library_GenerateChebyShevPolynomial
def Main(
SympyExpression= None,
DomainMinimumPoint= None,
DomainMaximumPoint= None,
ApproximationOrder= None,
CheckArguments = True,
PrintExtra = False,
):
#Tsymb = sympy.Symbol('t')
Xsymb = sympy.Symbol('x')
DomainStart = DomainMinimumPoint[0]
print 'DomainStart', DomainStart
DomainEnd = DomainMaximumPoint[0]
print 'DomainEnd', DomainEnd
#Transform the coefficients and the result to be on arbitrary inverval instead of from 0 to 1
DomainWidth = DomainEnd - DomainStart
DomainCenter = (DomainEnd - DomainStart) / 2.
t = (Xsymb*(DomainWidth) + DomainStart + DomainEnd) / 2.
x = (2.*Xsymb - DomainStart - DomainEnd) / (DomainWidth)
SympyExpression = SympyExpression.subs(Xsymb, t)
#GET THE COEFFICIENTS:
Coefficients = []
for CoefficientNumber in range(ApproximationOrder):
if(PrintExtra): print 'CoefficientNumber', CoefficientNumber
Coefficient = 0.0
for k in range(1, ApproximationOrder + 1):
if(PrintExtra): print ' k', k
CoefficientFunctionPart = SympyExpression.subs(Xsymb, sympy.cos( sympy.pi*( float(k) - .5 )/ float(ApproximationOrder) ) )
if(PrintExtra): print ' CoefficientFunctionPart', CoefficientFunctionPart
CeofficientCosArg = float(CoefficientNumber)*( float(k) - .5 )/ float( ApproximationOrder)
if(PrintExtra): print ' ',CoefficientNumber,'*','(',k,'-.5)/(', ApproximationOrder ,') == ', CeofficientCosArg
CoefficientCosPart = sympy.cos( sympy.pi*CeofficientCosArg )
if(PrintExtra): print ' CoefficientCosPart', CoefficientCosPart
Coefficient += CoefficientFunctionPart*CoefficientCosPart
if(PrintExtra): print 'Coefficient==', Coefficient
Coefficient = (2./ApproximationOrder)*Coefficient.evalf(10)
if(PrintExtra): print 'Coefficient==', Coefficient
Coefficients.append(Coefficient)
print '\n\nCoefficients'
pprint.pprint( Coefficients )
#GET THE POLYNOMIALS:
ChebyShevPolynomials = Library_GenerateChebyShevPolynomial.Main(
ResultType = 'sympy',
Kind= 1,
Order= ApproximationOrder-1,
ReturnAll = True,
)
print '\nChebyShevPolynomials'
pprint.pprint( ChebyShevPolynomials )
Result = 0.0 -.5*(Coefficients[0])
for Coefficient, ChebyShevPolynomial in zip(Coefficients, ChebyShevPolynomials):
Result += Coefficient*ChebyShevPolynomial
#Transform the coefficients and the result to be on arbitrary inverval instead of from 0 to 1
Result = Result.subs(Xsymb, x)
return Result
Example_SympyChebyShevApproximationOneDimension:
#------------------------------------------------------------------------------
import sympy
import sympy.mpmath
import matplotlib.pyplot as plt
import json
import pprint
import Library_GenerateBesselFunction
import Library_SympyChebyShevApproximationOneDimension
import Library_SympyExpressionToPythonFunction
import Library_GraphOneDimensionalFunction
ApproximationOrder = 10
#CREATE THE EXAMPLE EXRESSION:
Kind = 1
Order = 2
ExampleSympyExpression = sympy.sin(sympy.Symbol('x'))
"""
Library_GenerateBesselFunction.Main(
ResultType = 'sympy',
Kind = Kind,
Order = Order,
VariableNames = ['x'],
)
"""
PythonOriginalFunction = Library_SympyExpressionToPythonFunction.Main(
ExampleSympyExpression ,
FloatPrecision = 100,
)
#CREATE THE NATIVE CHEBY APPROXIMATION
ChebyDomainMin = 5.
ChebyDomainMax = 10.
ChebyDomain = [ChebyDomainMin, ChebyDomainMax]
ChebyExpandedPolynomialCoefficients, ChebyError = sympy.mpmath.chebyfit(
PythonOriginalFunction,
ChebyDomain,
ApproximationOrder,
error=True
)
print 'ChebyExpandedPolynomialCoefficients'
pprint.pprint( ChebyExpandedPolynomialCoefficients )
def PythonChebyChevApproximation(Point):
Result = sympy.mpmath.polyval(ChebyExpandedPolynomialCoefficients, Point)
return Result
#CREATE THE GENERIC ONE DIMENSIONAL CHEBY APPROXIMATION:
SympyChebyApproximation = Library_SympyChebyShevApproximationOneDimension.Main(
SympyExpression = ExampleSympyExpression*sympy.cos( sympy.Symbol('a') ),
ApproximationSymbol = sympy.Symbol('x'),
DomainMinimumPoint = [ChebyDomainMin],
DomainMaximumPoint = [ChebyDomainMax],
ApproximationOrder = ApproximationOrder
)
print 'SympyChebyApproximation', SympyChebyApproximation
SympyChebyApproximation = SympyChebyApproximation.subs(sympy.Symbol('a'), 0.0)
print 'SympyChebyApproximation', SympyChebyApproximation
PythonCastedChebyChevApproximationGeneric = Library_SympyExpressionToPythonFunction.Main(
SympyChebyApproximation ,
FloatPrecision = 100,
)
print 'PythonCastedChebyChevApproximationGeneric(1)', PythonCastedChebyChevApproximationGeneric(1.)