如果我有一個運算式x = Symbol('x')
,f1=x**2
并且我想進一步添加一些f2
scipyf2 = interp1d(t, y)
插值。一個人如何f2
變成一個運算式,使我有類似的東西f = x**2 f2(x)
,以便我以后可以評估f
為f.subs(x, some_number)
?
由于代碼的規范,我不能單獨評估f1
和f2
然后添加結果數字,我需要能夠將它添加到現有的 sympy 運算式并使用類似的東西來評估它.subs()
uj5u.com熱心網友回復:
一種方法,但它需要對要在類中呼叫的函式進行硬編碼:
f2 = lambda t: np.sin(t)
class MyFunc(Function):
@classmethod
def eval(cls, arg):
arg = sympify(arg, strict=True)
if arg.is_Number:
return sympify(f2(float(arg)), strict=True)
更像大衛的回答,但有幾個修復:
class FuncWrapper(Symbol):
"""Wraps a python callable as a Basic instance"""
def __new__(cls, func, name):
obj = super().__new__(cls, name)
obj._wrapped = func
return obj
@property
def wrapped(self):
return self._wrapped
def _hashable_content(self):
return (self.wrapped,) # needed for __eq__
def eval(self, arg):
if arg.is_Number:
return sympify(self.wrapped(float(arg)))
def __call__(self, arg):
return Call(self, arg)
class Call(Function):
@classmethod
def eval(cls, func, arg):
arg = sympify(arg)
result = func.eval(arg)
if result is not None:
return result
有了它,你有:
In [61]: f = FuncWrapper(np.sin, 'f')
In [62]: x f(x)
Out[62]: x Call(f, x)
In [63]: _.subs(x, 1)
Out[63]: 1.84147098480790
uj5u.com熱心網友回復:
一種非常危險的方法是為您的數值函式創建一個包裝器物件,如下所示:
from sympy import *
import numpy as np
var("x")
# symbolic expression
f1 = cos(x)
# numerical function
f2 = lambda t: np.sin(t)
class MyFunc(Expr):
"""Create a symbolic wrapper to a numerical function."""
def __new__(cls, arg, **kwargs):
obj = Expr.__new__(cls, **kwargs)
obj._custom_func = arg
return obj
def _subs(self, old, new, **hints):
return self._custom_func(float(new))
expr = f1 MyFunc(f2)
expr.subs(x, np.pi/4)
# out: 1.41421356237309
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484212.html