multiply matrix by i in Numpy [duplicate] - python

When I take the square root of -1 it gives me an error:
invalid value encountered in sqrt
How do I fix that?
from numpy import sqrt
arr = sqrt(-1)
print(arr)

To avoid the invalid value warning/error, the argument to numpy's sqrt function must be complex:
In [8]: import numpy as np
In [9]: np.sqrt(-1+0j)
Out[9]: 1j
As #AshwiniChaudhary pointed out in a comment, you could also use the cmath standard library:
In [10]: cmath.sqrt(-1)
Out[10]: 1j

I just discovered the convenience function numpy.lib.scimath.sqrt explained in the sqrt documentation. I use it as follows:
>>> from numpy.lib.scimath import sqrt as csqrt
>>> csqrt(-1)
1j

You need to use the sqrt from the cmath module (part of the standard library)
>>> import cmath
>>> cmath.sqrt(-1)
1j

The latest addendum to the Numpy Documentation here, adds the command numpy.emath.sqrt which returns the complex numbers when the negative numbers are fed to the square root sign in a operation.

The square root of -1 is not a real number, but rather an imaginary number. IEEE 754 does not have a way of representing imaginary numbers.
numpy has support for complex numbers. I suggest you use that: http://docs.scipy.org/doc/numpy/user/basics.types.html

Others have probably suggested more desirable methods, but just to add to the conversation, you could always multiply any number less than 0 (the value you want the sqrt of, -1 in this case) by -1, then take the sqrt of that. Just know then that your result is imaginary.

Related

Dynamic decimal point Python float

I'm looking for a way to neatly show rounded floats of varying decimal lengh.
Example of what I'm looking for:
In: 0.0000000071234%
Out: 0.0000000071%
In: 0.00061231999999%
Out: 0.0061%
In: 0.149999999%
Out: 0.15%
One way to do it would be:
def dynamic_round(num):
zeros = 2
original = num
while num< 0.1:
num*= 10
zeros += 1
return round(original, zeros)
I'm sure however there is a much cleaner way to do the same thing.
Here's a way to do it without a loop:
a = 0.003123
log10 = -int(math.log10(a))
res = round(a, log10+2)
==> 0.0031
This post answers your question with a similar logic
How can I format a decimal to always show 2 decimal places?
but just to clarify
One way would be to use round() function also mentioned in the documentation
built-in functions: round()
>>> round(number[,digits])
here digit refers to the precision after decimal point and is optional as well.
Alternatively, you can also use new format specifications
>>> from math import pi # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'
here the number next to f tells the precision and f refers to float.
Another way to go here is to import numpy
>>>import numpy
>>>a=0.0000327123
>>>res=-int(numpy.log10(a))
>>>round(a,res+2)
>>>0.000033
numpy.log() also, takes an array as an argument, so if you have multiple values you can iterate through the array.

Exponent an arbitrary number by a numpy array

I know np.exp2(x) exists that calculates 2^x where x is a numpy array, however, I am looking for a method that does K^x where K is any arbitrary number.
Is there any elegant way of doing it rather than stretching out K to the shape of x and doing a piecewise exponent?
Just use the standard Python exponentiation operator **:
K**x
For example, if you have:
x = np.array([1,2,3])
K = 3
print(K**x)
The output is:
[ 3 9 27]
Notes
For Python classes, the behavior of the binary ** operator is implemented via the __pow__, __rpow__, and __ipow__ magic methods (the reality for np.ndarray is slightly more complicated since it's implemented in the C layer, but that's not actually important here). For Numpy arrays, these magic methods in turn appear to call numpy.power, so you can expect that ** will have the same behavior as documented for numpy.power. In particular,
Note that an integer type raised to a negative integer power will raise a ValueError.
With numpy you can just use numpy.power
arr = numpy.array([1,2,3])
print(numpy.power(3,arr)) # Outputs [ 3 9 27]

Smallest positive float64 number

I need to find a numpy.float64 value that is as close to zero as possible.
Numpy offers several constants that allow to do something similar:
np.finfo(np.float64).eps = 2.2204460492503131e-16
np.finfo(np.float64).tiny = 2.2250738585072014e-308
These are both reasonably small, but when I do this
>>> x = np.finfo(np.float64).tiny
>>> x / 2
6.9533558078350043e-310
the result is even smaller. When using an impromptu binary search I can get down to about 1e-323, before the value is rounded down to 0.0.
Is there a constant for this in numpy that I am missing? Alternatively, is there a right way to do this?
Use np.nextafter.
>>> import numpy as np
>>> np.nextafter(0, 1)
4.9406564584124654e-324
>>> np.nextafter(np.float32(0), np.float32(1))
1.4012985e-45
2^-1075 is the smallest positive float.
2^-1075 = 5.10^-324

numpy.arctanh(x) for x >= 1 returns NaN but I want complex

When I perform the operation numpy.arctanh(x) for x >= 1, it returns nan, which is odd because when I perform the operation in Wolfram|alpha, it returns complex values, which is what I need for my application.
Does anyone know what I can do to keep Numpy from suppressing complex values?
Add +0j to your real inputs to make them complex numbers.
Numpy is following a variation of the maxim "Garbage in, Garbage out."
Float in, float out.
>>> import numpy as np
>>> np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan
Complex in, complex out.
>>> numpy.sqrt(-1+0j)
1j
>>> numpy.arctanh(24+0j)
(0.0416908044695255-1.5707963267948966j)

math overflow for a not very overflowing calculation in python

The calculation for which I'm getting the math overflow number is:
e2 = math.exp([[-20.7313399283991]])
There are actually more extreme numbers that I've done than this, why is this causing an overflow?
I get this error:
OverflowError: math range error
math.exp() operates on scalars, not on matrices.
You can use it like so, without the square brackets:
>>> math.exp(-20.7313399283991)
9.919584164742123e-10
If you need to operate on a matrix, you could use numpy.exp():
>>> numpy.exp([[-20.7313399283991]])
array([[ 9.91958416e-10]])
This computes the element-by-element e**x and returns an array of the same shape as the input. (Note that this is not the same as the matrix exponential; for that, there is scipy.linalg.expm().)
You should call it without the [[]]:
e2 = math.exp(-20.7313399283991)

Categories