1
======================================
2
Python IEEE 754 floating point support
3
======================================
5
>>> from sys import float_info as FI
10
You must never compare two floats with == because you are not going to get
11
what you expect. We treat two floats as equal if the difference between them
12
is small than epsilon.
15
... """Almost equal helper for floats"""
16
... return abs(x - y) < EPS
22
In Python 2.6 and newer NaNs (not a number) and infinity can be constructed
23
from the strings 'inf' and 'nan'.
25
>>> INF = float('inf')
26
>>> NINF = float('-inf')
27
>>> NAN = float('nan')
36
The math module's ``isnan`` and ``isinf`` functions can be used to detect INF
38
>>> isinf(INF), isinf(NINF), isnan(NAN)
46
Ambiguous operations like ``0 * inf`` or ``inf - inf`` result in NaN.
54
However unambigous operations with inf return inf:
67
NaNs are never equal to another number, even itself
75
All operations involving a NaN return a NaN except for the power of *0* and *1*.
86
>>> (1.0 + FI.epsilon) * NAN
92
The power of 1 raised to x is always 1.0, even for special values like 0,
104
The power of 0 raised to x is defined as 0, if x is positive. Negative
105
values are a domain error or zero division error and NaN result in a
113
Traceback (most recent call last):
115
ValueError: math domain error
117
Traceback (most recent call last):
119
ZeroDivisionError: 0.0 cannot be raised to a negative power
124
Trigonometric Functions
125
=======================
128
Traceback (most recent call last):
130
ValueError: math domain error
132
Traceback (most recent call last):
134
ValueError: math domain error
138
Traceback (most recent call last):
140
ValueError: math domain error
142
Traceback (most recent call last):
144
ValueError: math domain error
148
Traceback (most recent call last):
150
ValueError: math domain error
152
Traceback (most recent call last):
154
ValueError: math domain error
158
Neither pi nor tan are exact, but you can assume that tan(pi/2) is a large value
159
and tan(pi) is a very small value:
162
>>> -tan(-PI/2) > 1E10
167
>>> asin(NAN), acos(NAN), atan(NAN)
169
>>> asin(INF), asin(NINF)
170
Traceback (most recent call last):
172
ValueError: math domain error
173
>>> acos(INF), acos(NINF)
174
Traceback (most recent call last):
176
ValueError: math domain error
177
>>> equal(atan(INF), PI/2), equal(atan(NINF), -PI/2)