Error Using 'exp' In Sympy -typeerror And Attribute Error Is Displayed
Solution 1:
In an isympy
session (similar to your imports), plus a np
import:
In [12]: data = [1,2,3,4,5]
In [13]: np.power(data,c)
Out[13]: array([1, 2**c, 3**c, 4**c, 5**c], dtype=object)
In [14]: b*c*np.power(data,c)
Out[14]: array([b*c, 2**c*b*c, 3**c*b*c, 4**c*b*c, 5**c*b*c], dtype=object)
So far these work. When numpy
functions and operators encounter an object dtype array (non-numeric ones), they try to apply corresponding operators or methods of the objects. b
and c
as symbols
do respond to **
and *
.
But np.log
applied to the object array fails with your error message. The elements of the array a sympy Mul
objects:
In [17]: type(Out[14][0])
Out[17]: sympy.core.mul.Mul
In [18]: Out[14][0].log()
---------------------------------------------------------------------------
AttributeError: 'Mul' object has no attribute 'log'
Same for np.exp
.
math.log
expects a number, so it won't work with array or the sympy objects either.
sympy.log(Out[14][0])
works - the argument is a sympy Mul
. But it doesn't work with Out[14]
which a numpy array.
===
I know numpy
a lot better than sympy
. But I was able to get this sequence of calculations to work:
In[24]: [d**c for d in data] # listcomprehensionOut[24]:
⎡ cccc⎤
⎣1, 2 , 3 , 4 , 5 ⎦
In[25]: [b*c*num**c for num in data]Out[25]:
⎡ cccc ⎤
⎣b⋅c, 2 ⋅b⋅c, 3 ⋅b⋅c, 4 ⋅b⋅c, 5 ⋅b⋅c⎦
In[26]: [log(b*c*num**c) for num in data]Out[26]:
⎡ ⎛ c ⎞ ⎛ c ⎞ ⎛ c ⎞ ⎛ c ⎞⎤
⎣log(b⋅c), log⎝2 ⋅b⋅c⎠, log⎝3 ⋅b⋅c⎠, log⎝4 ⋅b⋅c⎠, log⎝5 ⋅b⋅c⎠⎦
In[27]: sum([log(b*c*num**c) for num in data])
Out[27]:
⎛ c ⎞ ⎛ c ⎞ ⎛ c ⎞ ⎛ c ⎞
log(b⋅c) + log⎝2 ⋅b⋅c⎠ + log⎝3 ⋅b⋅c⎠ + log⎝4 ⋅b⋅c⎠ + log⎝5 ⋅b⋅c⎠
sympy.sum
expects an iterable, which this list qualifies.
Now I can do the sympy.diff
In[29]: diff(sum([log(b*c*num**c) for num in data]),b)
Out[29]:
5
─
bIn[30]: diff(sum([log(b*c*num**c) for num in data]),c)
Out[30]:
-c ⎛ cc ⎞ -c ⎛ cc ⎞ -c ⎛ c15 ⋅⎝5 ⋅b⋅c⋅log(5) + 5 ⋅b⎠ 4 ⋅⎝4 ⋅b⋅c⋅log(4) + 4 ⋅b⎠ 3 ⋅⎝3 ⋅b⋅c⋅l
─ + ────────────────────────── + ────────────────────────── + ─────────────
cb⋅cb⋅cb⋅
c ⎞ -c ⎛ cc ⎞
og(3) + 3 ⋅b⎠ 2 ⋅⎝2 ⋅b⋅c⋅log(2) + 2 ⋅b⎠
───────────── + ──────────────────────────
cb⋅c
[log(item) for item in Out[14]]
produces the same output as Out[26]
. Out[14]
is simply the object array equivalent of the Out[25]
list.
Solution 2:
As per @hpaulj suggestion, I was able to solve this by using list comprehension. The working code is below:
f =-(-n +sum([sym.log(b*c*(num**(c-1))*sym.exp(-b*(num**c)))for num in data]))
Post a Comment for "Error Using 'exp' In Sympy -typeerror And Attribute Error Is Displayed"