alec_djinn
alec_djinn

Reputation: 10799

python strange result using math.fmod()

I am playing around with the math module in Python 3.4 and I got some curious results when using fmod function for which I am having hard times in getting detailed info from the python website.

One simple example is the following:

from math import *

x = 99809175801648148531
y = 6.5169020832937505
sqrt(x)-cos(x)**fmod(x, y)*log10(x)

it returns:

(9990454237.014296+8.722374238018135j)

How to interpret this result? What is j? Is it an imaginary number like i? If so, why j and not i? Any info, as well as links to some resources about fmod are very welcome.

Upvotes: 1

Views: 299

Answers (3)

user1245262
user1245262

Reputation: 7505

cos(x) is a negative number. When you raise a negative number to a non-integral power, it is not surprising to get a complex result. Most roots of negative numbers are complex.

>>> x = 99809175801648148531
>>> y = 6.5169020832937505

>>> cos(x)
-0.7962325418899466
>>> fmod(x,y)
3.3940870272073056
>>> cos(x)**fmod(x,y)
(-0.1507219382442201-0.436136801343955j)

Imaginary numbers can be represented with either an 'i' or a 'j'. I believe the reasons are historical. Mathematicians prefered 'i' for imaginary. Electrical engineers didn't want to get an imaginary 'i' confused with an 'i' for current, so they used 'j'. Now, both are used.

Upvotes: 0

NPE
NPE

Reputation: 500447

Here, j is the same as i, the square root of -1. It is a convention commonly used in engineering, where i is used to denote electrical current.

The reason complex numbers arise in your case is that you're raising a negative number to a fractional power. See How do you compute negative numbers to fractional powers? for further discussion.

Upvotes: 0

shuttle87
shuttle87

Reputation: 15934

The result you got was a complex number because you exponentiated a negative number. i and j are just notational choices to represent the imaginary number unit, i being used in mathematics more and j being used in engineering more. You can see in the docs that Python has chosen to use j:

https://docs.python.org/2/library/cmath.html#conversions-to-and-from-polar-coordinates

Upvotes: 1

Related Questions