1NumPy core libraries
2====================
3
4.. sectionauthor:: David Cournapeau
5
6.. versionadded:: 1.3.0
7
8Starting from numpy 1.3.0, we are working on separating the pure C,
9"computational" code from the python dependent code. The goal is twofolds:
10making the code cleaner, and enabling code reuse by other extensions outside
11numpy (scipy, etc...).
12
13NumPy core math library
14-----------------------
15
16The numpy core math library ('npymath') is a first step in this direction. This
17library contains most math-related C99 functionality, which can be used on
18platforms where C99 is not well supported. The core math functions have the
19same API as the C99 ones, except for the npy_* prefix.
20
21The available functions are defined in <numpy/npy_math.h> - please refer to this header when
22in doubt.
23
24Floating point classification
25~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26
27.. c:macro:: NPY_NAN
28
29    This macro is defined to a NaN (Not a Number), and is guaranteed to have
30    the signbit unset ('positive' NaN). The corresponding single and extension
31    precision macro are available with the suffix F and L.
32
33.. c:macro:: NPY_INFINITY
34
35    This macro is defined to a positive inf. The corresponding single and
36    extension precision macro are available with the suffix F and L.
37
38.. c:macro:: NPY_PZERO
39
40    This macro is defined to positive zero. The corresponding single and
41    extension precision macro are available with the suffix F and L.
42
43.. c:macro:: NPY_NZERO
44
45    This macro is defined to negative zero (that is with the sign bit set). The
46    corresponding single and extension precision macro are available with the
47    suffix F and L.
48
49.. c:function:: int npy_isnan(x)
50
51    This is a macro, and is equivalent to C99 isnan: works for single, double
52    and extended precision, and return a non 0 value is x is a NaN.
53
54.. c:function:: int npy_isfinite(x)
55
56    This is a macro, and is equivalent to C99 isfinite: works for single,
57    double and extended precision, and return a non 0 value is x is neither a
58    NaN nor an infinity.
59
60.. c:function:: int npy_isinf(x)
61
62    This is a macro, and is equivalent to C99 isinf: works for single, double
63    and extended precision, and return a non 0 value is x is infinite (positive
64    and negative).
65
66.. c:function:: int npy_signbit(x)
67
68    This is a macro, and is equivalent to C99 signbit: works for single, double
69    and extended precision, and return a non 0 value is x has the signbit set
70    (that is the number is negative).
71
72.. c:function:: double npy_copysign(double x, double y)
73
74    This is a function equivalent to C99 copysign: return x with the same sign
75    as y. Works for any value, including inf and nan. Single and extended
76    precisions are available with suffix f and l.
77
78    .. versionadded:: 1.4.0
79
80Useful math constants
81~~~~~~~~~~~~~~~~~~~~~
82
83The following math constants are available in ``npy_math.h``. Single
84and extended precision are also available by adding the ``f`` and
85``l`` suffixes respectively.
86
87.. c:macro:: NPY_E
88
89    Base of natural logarithm (:math:`e`)
90
91.. c:macro:: NPY_LOG2E
92
93    Logarithm to base 2 of the Euler constant (:math:`\frac{\ln(e)}{\ln(2)}`)
94
95.. c:macro:: NPY_LOG10E
96
97    Logarithm to base 10 of the Euler constant (:math:`\frac{\ln(e)}{\ln(10)}`)
98
99.. c:macro:: NPY_LOGE2
100
101    Natural logarithm of 2 (:math:`\ln(2)`)
102
103.. c:macro:: NPY_LOGE10
104
105    Natural logarithm of 10 (:math:`\ln(10)`)
106
107.. c:macro:: NPY_PI
108
109    Pi (:math:`\pi`)
110
111.. c:macro:: NPY_PI_2
112
113    Pi divided by 2 (:math:`\frac{\pi}{2}`)
114
115.. c:macro:: NPY_PI_4
116
117    Pi divided by 4 (:math:`\frac{\pi}{4}`)
118
119.. c:macro:: NPY_1_PI
120
121    Reciprocal of pi (:math:`\frac{1}{\pi}`)
122
123.. c:macro:: NPY_2_PI
124
125    Two times the reciprocal of pi (:math:`\frac{2}{\pi}`)
126
127.. c:macro:: NPY_EULER
128
129    The Euler constant
130        :math:`\lim_{n\rightarrow\infty}({\sum_{k=1}^n{\frac{1}{k}}-\ln n})`
131
132Low-level floating point manipulation
133~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
134
135Those can be useful for precise floating point comparison.
136
137.. c:function:: double npy_nextafter(double x, double y)
138
139    This is a function equivalent to C99 nextafter: return next representable
140    floating point value from x in the direction of y. Single and extended
141    precisions are available with suffix f and l.
142
143    .. versionadded:: 1.4.0
144
145.. c:function:: double npy_spacing(double x)
146
147    This is a function equivalent to Fortran intrinsic. Return distance between
148    x and next representable floating point value from x, e.g. spacing(1) ==
149    eps. spacing of nan and +/- inf return nan. Single and extended precisions
150    are available with suffix f and l.
151
152    .. versionadded:: 1.4.0
153
154.. c:function:: void npy_set_floatstatus_divbyzero()
155
156    Set the divide by zero floating point exception
157
158    .. versionadded:: 1.6.0
159
160.. c:function:: void npy_set_floatstatus_overflow()
161
162    Set the overflow floating point exception
163
164    .. versionadded:: 1.6.0
165
166.. c:function:: void npy_set_floatstatus_underflow()
167
168    Set the underflow floating point exception
169
170    .. versionadded:: 1.6.0
171
172.. c:function:: void npy_set_floatstatus_invalid()
173
174    Set the invalid floating point exception
175
176    .. versionadded:: 1.6.0
177
178.. c:function:: int npy_get_floatstatus()
179
180    Get floating point status. Returns a bitmask with following possible flags:
181
182    * NPY_FPE_DIVIDEBYZERO
183    * NPY_FPE_OVERFLOW
184    * NPY_FPE_UNDERFLOW
185    * NPY_FPE_INVALID
186
187    Note that :c:func:`npy_get_floatstatus_barrier` is preferable as it prevents
188    aggressive compiler optimizations reordering the call relative to
189    the code setting the status, which could lead to incorrect results.
190
191    .. versionadded:: 1.9.0
192
193.. c:function:: int npy_get_floatstatus_barrier(char*)
194
195    Get floating point status. A pointer to a local variable is passed in to
196    prevent aggressive compiler optimizations from reordering this function call
197    relative to the code setting the status, which could lead to incorrect
198    results.
199
200    Returns a bitmask with following possible flags:
201
202    * NPY_FPE_DIVIDEBYZERO
203    * NPY_FPE_OVERFLOW
204    * NPY_FPE_UNDERFLOW
205    * NPY_FPE_INVALID
206
207    .. versionadded:: 1.15.0
208
209.. c:function:: int npy_clear_floatstatus()
210
211    Clears the floating point status. Returns the previous status mask.
212
213    Note that :c:func:`npy_clear_floatstatus_barrier` is preferable as it
214    prevents aggressive compiler optimizations reordering the call relative to
215    the code setting the status, which could lead to incorrect results.
216
217    .. versionadded:: 1.9.0
218
219.. c:function:: int npy_clear_floatstatus_barrier(char*)
220
221    Clears the floating point status. A pointer to a local variable is passed in to
222    prevent aggressive compiler optimizations from reordering this function call.
223    Returns the previous status mask.
224
225    .. versionadded:: 1.15.0
226
227Complex functions
228~~~~~~~~~~~~~~~~~
229
230.. versionadded:: 1.4.0
231
232C99-like complex functions have been added. Those can be used if you wish to
233implement portable C extensions. Since we still support platforms without C99
234complex type, you need to restrict to C90-compatible syntax, e.g.:
235
236.. code-block:: c
237
238        /* a = 1 + 2i \*/
239        npy_complex a = npy_cpack(1, 2);
240        npy_complex b;
241
242        b = npy_log(a);
243
244Linking against the core math library in an extension
245~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
246
247.. versionadded:: 1.4.0
248
249To use the core math library in your own extension, you need to add the npymath
250compile and link options to your extension in your setup.py:
251
252        .. hidden in a comment so as to be included in refguide but not rendered documentation
253                >>> import numpy.distutils.misc_util
254                >>> config = np.distutils.misc_util.Configuration(None, '', '.')
255                >>> with open('foo.c', 'w') as f: pass
256
257        >>> from numpy.distutils.misc_util import get_info
258        >>> info = get_info('npymath')
259        >>> _ = config.add_extension('foo', sources=['foo.c'], extra_info=info)
260
261In other words, the usage of info is exactly the same as when using blas_info
262and co.
263
264Half-precision functions
265~~~~~~~~~~~~~~~~~~~~~~~~
266
267.. versionadded:: 1.6.0
268
269The header file <numpy/halffloat.h> provides functions to work with
270IEEE 754-2008 16-bit floating point values. While this format is
271not typically used for numerical computations, it is useful for
272storing values which require floating point but do not need much precision.
273It can also be used as an educational tool to understand the nature
274of floating point round-off error.
275
276Like for other types, NumPy includes a typedef npy_half for the 16 bit
277float.  Unlike for most of the other types, you cannot use this as a
278normal type in C, since it is a typedef for npy_uint16.  For example,
2791.0 looks like 0x3c00 to C, and if you do an equality comparison
280between the different signed zeros, you will get -0.0 != 0.0
281(0x8000 != 0x0000), which is incorrect.
282
283For these reasons, NumPy provides an API to work with npy_half values
284accessible by including <numpy/halffloat.h> and linking to 'npymath'.
285For functions that are not provided directly, such as the arithmetic
286operations, the preferred method is to convert to float
287or double and back again, as in the following example.
288
289.. code-block:: c
290
291        npy_half sum(int n, npy_half *array) {
292            float ret = 0;
293            while(n--) {
294                ret += npy_half_to_float(*array++);
295            }
296            return npy_float_to_half(ret);
297        }
298
299External Links:
300
301* `754-2008 IEEE Standard for Floating-Point Arithmetic`__
302* `Half-precision Float Wikipedia Article`__.
303* `OpenGL Half Float Pixel Support`__
304* `The OpenEXR image format`__.
305
306__ https://ieeexplore.ieee.org/document/4610935/
307__ https://en.wikipedia.org/wiki/Half-precision_floating-point_format
308__ https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_half_float_pixel.txt
309__ https://www.openexr.com/about.html
310
311.. c:macro:: NPY_HALF_ZERO
312
313    This macro is defined to positive zero.
314
315.. c:macro:: NPY_HALF_PZERO
316
317    This macro is defined to positive zero.
318
319.. c:macro:: NPY_HALF_NZERO
320
321    This macro is defined to negative zero.
322
323.. c:macro:: NPY_HALF_ONE
324
325    This macro is defined to 1.0.
326
327.. c:macro:: NPY_HALF_NEGONE
328
329    This macro is defined to -1.0.
330
331.. c:macro:: NPY_HALF_PINF
332
333    This macro is defined to +inf.
334
335.. c:macro:: NPY_HALF_NINF
336
337    This macro is defined to -inf.
338
339.. c:macro:: NPY_HALF_NAN
340
341    This macro is defined to a NaN value, guaranteed to have its sign bit unset.
342
343.. c:function:: float npy_half_to_float(npy_half h)
344
345   Converts a half-precision float to a single-precision float.
346
347.. c:function:: double npy_half_to_double(npy_half h)
348
349   Converts a half-precision float to a double-precision float.
350
351.. c:function:: npy_half npy_float_to_half(float f)
352
353   Converts a single-precision float to a half-precision float.  The
354   value is rounded to the nearest representable half, with ties going
355   to the nearest even.  If the value is too small or too big, the
356   system's floating point underflow or overflow bit will be set.
357
358.. c:function:: npy_half npy_double_to_half(double d)
359
360   Converts a double-precision float to a half-precision float.  The
361   value is rounded to the nearest representable half, with ties going
362   to the nearest even.  If the value is too small or too big, the
363   system's floating point underflow or overflow bit will be set.
364
365.. c:function:: int npy_half_eq(npy_half h1, npy_half h2)
366
367   Compares two half-precision floats (h1 == h2).
368
369.. c:function:: int npy_half_ne(npy_half h1, npy_half h2)
370
371   Compares two half-precision floats (h1 != h2).
372
373.. c:function:: int npy_half_le(npy_half h1, npy_half h2)
374
375   Compares two half-precision floats (h1 <= h2).
376
377.. c:function:: int npy_half_lt(npy_half h1, npy_half h2)
378
379   Compares two half-precision floats (h1 < h2).
380
381.. c:function:: int npy_half_ge(npy_half h1, npy_half h2)
382
383   Compares two half-precision floats (h1 >= h2).
384
385.. c:function:: int npy_half_gt(npy_half h1, npy_half h2)
386
387   Compares two half-precision floats (h1 > h2).
388
389.. c:function:: int npy_half_eq_nonan(npy_half h1, npy_half h2)
390
391   Compares two half-precision floats that are known to not be NaN (h1 == h2).  If
392   a value is NaN, the result is undefined.
393
394.. c:function:: int npy_half_lt_nonan(npy_half h1, npy_half h2)
395
396   Compares two half-precision floats that are known to not be NaN (h1 < h2).  If
397   a value is NaN, the result is undefined.
398
399.. c:function:: int npy_half_le_nonan(npy_half h1, npy_half h2)
400
401   Compares two half-precision floats that are known to not be NaN (h1 <= h2).  If
402   a value is NaN, the result is undefined.
403
404.. c:function:: int npy_half_iszero(npy_half h)
405
406   Tests whether the half-precision float has a value equal to zero.  This may be slightly
407   faster than calling npy_half_eq(h, NPY_ZERO).
408
409.. c:function:: int npy_half_isnan(npy_half h)
410
411   Tests whether the half-precision float is a NaN.
412
413.. c:function:: int npy_half_isinf(npy_half h)
414
415   Tests whether the half-precision float is plus or minus Inf.
416
417.. c:function:: int npy_half_isfinite(npy_half h)
418
419   Tests whether the half-precision float is finite (not NaN or Inf).
420
421.. c:function:: int npy_half_signbit(npy_half h)
422
423   Returns 1 is h is negative, 0 otherwise.
424
425.. c:function:: npy_half npy_half_copysign(npy_half x, npy_half y)
426
427    Returns the value of x with the sign bit copied from y.  Works for any value,
428    including Inf and NaN.
429
430.. c:function:: npy_half npy_half_spacing(npy_half h)
431
432    This is the same for half-precision float as npy_spacing and npy_spacingf
433    described in the low-level floating point section.
434
435.. c:function:: npy_half npy_half_nextafter(npy_half x, npy_half y)
436
437    This is the same for half-precision float as npy_nextafter and npy_nextafterf
438    described in the low-level floating point section.
439
440.. c:function:: npy_uint16 npy_floatbits_to_halfbits(npy_uint32 f)
441
442   Low-level function which converts a 32-bit single-precision float, stored
443   as a uint32, into a 16-bit half-precision float.
444
445.. c:function:: npy_uint16 npy_doublebits_to_halfbits(npy_uint64 d)
446
447   Low-level function which converts a 64-bit double-precision float, stored
448   as a uint64, into a 16-bit half-precision float.
449
450.. c:function:: npy_uint32 npy_halfbits_to_floatbits(npy_uint16 h)
451
452   Low-level function which converts a 16-bit half-precision float
453   into a 32-bit single-precision float, stored as a uint32.
454
455.. c:function:: npy_uint64 npy_halfbits_to_doublebits(npy_uint16 h)
456
457   Low-level function which converts a 16-bit half-precision float
458   into a 64-bit double-precision float, stored as a uint64.
459