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"