Reputation: 23
I'm trying to make a matplotlib plot of the function logi(x) (an i-based log). Here is my code:
from pylab import *
import cmath
x = linspace(-8,8,500)
z = cmath.log(x,1j)
plot(x,real(z),label='real')
plot(x,imag(z),label='imag')
legend()
show()
The problem is that it throws TypeError: only length-1 arrays can be converted to Python scalars
.
I've searched a bit and found answers such as TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data :
Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays.
And some advice that says to use Numpy's log() function instead. Unfortunately Numpy does not support i-based logarithms so I'm forced to use Cmath. How can I fix it?
Upvotes: 0
Views: 116
Reputation: 231325
If the array has complex dtype, then np.log
will return complex results:
In [58]: x = np.linspace(-8,8,11).astype(complex)
In [59]: x
Out[59]:
array([-8. +0.j, -6.4+0.j, -4.8+0.j, -3.2+0.j, -1.6+0.j, 0. +0.j,
1.6+0.j, 3.2+0.j, 4.8+0.j, 6.4+0.j, 8. +0.j])
In [60]: np.log(x)
C:\Users\paul\AppData\Local\Temp\ipykernel_7972\1277889159.py:1: RuntimeWarning: divide by zero encountered in log
np.log(x)
Out[60]:
array([2.07944154+3.14159265j, 1.85629799+3.14159265j,
1.56861592+3.14159265j, 1.16315081+3.14159265j,
0.47000363+3.14159265j, -inf+0.j ,
0.47000363+0.j , 1.16315081+0.j ,
1.56861592+0.j , 1.85629799+0.j ,
2.07944154+0.j ])
At -8:
In [61]: np.log(x[0])
Out[61]: (2.0794415416798357+3.141592653589793j)
We can shift the base with the standard:
In [62]: np.log(x[0])/np.log(1j)
Out[62]: (2-1.3238136009159096j)
Compare that with cmath
result:
In [63]: cmath.log(-8, 1j)
Out[63]: (2-1.3238136009159096j)
So either iterate and call cmath.log
for each element of the array, or use this complex array and base shift.
Upvotes: 0