Pythonはシンボル演算を実現
2980 ワード
Pythonにはシンボル演算ライブラリが付属しています
from symbol import *
E
と複素単位I
>>>x = Symbol('x', real=True)
>>>y = Symbol('y', real=True)
>>>(x+y)**2
(x + y)**2
>>>expand((x+y)**2, real=True)
x**2 + 2*x*y + y**2
python実装演算
class array(object):
def __init__(self, value, name=None):
self.value = value
if name:
self.grad = lambda g: {name : g}
# ,
# '+'
def __add__(self, other):
assert isinstance(other, int)
ret = array(self.value+other)
ret.grad = self.grad
return ret
# '*'
def __mul__(self, other):
assert isinstance(other, array)
ret = array(self.value*other.value)
def grad(g):
x = self.grad(g*other.value)
x.update(other.grad(self.value*g))
# x*y, x(self) y(other),
return x
ret.grad = grad
return ret
x = array(1, 'x')
y = array(2, 'y')
w = x*y
z = w + 1
print(z.value)
print(z.grad(1))
# z.grad , ,