Aguy - 9 months ago 24

Python Question

Sorry for the unusual title... :-)

Using

`import numpy as np`

`np.tan(np.pi/2)`

gives the number in the title and not

`np.inf`

`16331239353195370.0`

I'm curious about this number. Is it related to some system machine precision parameter? Could I have calculated it from something? (I'm thinking along the lines of something similar to

`sys.float_info`

Answer

`pi`

isn't exactly representable as Python float (same as the platform C's `double`

type). The closest representable approximation is used.

Here's the exact approximation in use on my box (probably the same as on your box):

```
>>> import math
>>> (math.pi / 2).as_integer_ratio()
(884279719003555, 562949953421312)
```

To find the tangent of that ratio, I'm going to switch to wxMaxima now:

```
(%i1) fpprec: 32;
(%o1) 32
(%i2) tan(bfloat(884279719003555) / 562949953421312);
(%o2) 1.6331239353195369755967737041529b16
```

So essentially identical to what you got. The binary approximation to `pi/2`

used is a little bit less than the mathematical ("infinite precision") value of `pi/2`

. So you get a very large tangent instead of `infinity`

. The computed `tan()`

is appropriate for the actual input!

For exactly the same kinds of reasons, e.g.,

```
>>> math.sin(math.pi)
1.2246467991473532e-16
```

doesn't return 0. The approximation `math.pi`

is a little bit less than `pi`

, and the displayed result is correct *given* that truth.