Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
imaginary number i
#1
I was trying the following commands :

>>> -1 ** 0.5
-1.0
>>> (-1) ** 0.5
(6.123233995736766e-17+1j)
I was expecting "1j" , "1i" or "i"


I am just surprised to find different values for the same problem.

I was expecting to see that python has higher priority of "sign" over the power "**"

any reason for those results?
Reply
#2
The second one is 1j to within the precision of the computation. Floating point math isn't necessarily exact. https://docs.python.org/3/tutorial/floatingpoint.html
Reply
#3
The reason -1**0.5 == -1 is that ** has higher precedence than unary -.

The reason (-1)**5 ~= 1j is that the parenthesis change the order of operations. Unary - is first, then **. As for the small remainder,
you don't need imaginary numbers to see that you cannot represent an infinite set of numbers using a limited set of bytes.
mr_byte31 likes this post
Reply
#4
then why the first one not correct??

>>> -1 ** 0.5
-1.0
Reply
#5
The first one IS correct.
The square root of 1 is 1
Then apply the unary minus and you get -1
Reply
#6
(Sep-23-2021, 04:01 PM)mr_byte31 Wrote: then why the first one not correct??

>>> -1 ** 0.5
-1.0

As mentioned, the precedence rules mean the exponentiation happens first. The effect is the same as
- (1 ** 0.5)
Operator precedence
Reply
#7
It gets really confusing when it looks like Python can exactly represent all the numbers involved. Why is 0.3 not 0.3?
print(0.1, 0.2, 0.1 + 0.2, 0.3)
Output:
0.1 0.2 0.30000000000000004 0.3
mr_byte31 likes this post
Reply
#8
(Sep-23-2021, 03:59 PM)deanhystad Wrote: The reason -1**0.5 == -1 is that ** has higher precedence than unary -.

The reason (-1)**5 ~= 1j is that the parenthesis change the order of operations. Unary - is first, then **. As for the small remainder,
you don't need imaginary numbers to see that you cannot represent an infinite set of numbers using a limited set of bytes.

This is the first programming language that I see to give priority to "power" than to sign "-"
Reply
#9
(Sep-23-2021, 04:28 PM)mr_byte31 Wrote: This is the first programming language that I see to give priority to "power" than to sign "-"

https://math.stackexchange.com/q/1299236

And one of the answers gives an example - FORTRAN
Same precedence in Matlab - https://www.mathworks.com/help/matlab/ma...dence.html
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020