Just curious how are these implemented. I can't see where I would start. Do they work directly on the float
's/double
's bits?
Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.
EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil()
and floor()
functions.
The Python ceil() function rounds a number up to the nearest integer, or whole number. Python floor() rounds decimals down to the nearest whole number. Both of these functions are part of the math Python library.
The floor() function: floor() method in Python returns the floor of x i.e., the largest integer not greater than x. Syntax: import math math. floor(x) Parameter: x-numeric expression. Returns: largest integer not greater than x.
Math. ceil() - rounds the number to a higher value. Math. floor() - rounds the number to a lower value.
If you're interested in seeing source code for algorithms for this kind of thing, then fdlibm - the "Freely Distributable libm
", originally from Sun, and the reference implementation for Java's math libraries - might be a good place to start. (For casual browsing, it's certainly a better place to start than GNU libc, where the pieces are scattered around various subdirectories - math/
, sysdeps/ieee754/
, etc.)
fdlibm assumes that it's working with an IEEE 754 format double
, and if you look at the implementations - for example, the core of the implementation of log() - you'll see that they use all sorts of clever tricks, often using a mixture of both standard double
arithmetic, and knowledge of the bit representation of a double
.
(And if you're interested in algorithms for supporting basic IEEE 754 floating point arithmetic, such as might be used for processors without hardware floating point support, take a look at John R. Hauser's SoftFloat.)
As for your edit: in general, ceil()
and floor()
might well be implemented in hardware; for example, on x86, GCC (with optimisations enabled) generates code using the frndint
instruction with appropriate fiddling of the FPU control word to set the rounding mode. But fdlibm's pure software implementations (s_ceil.c
, s_floor.c
) do work using the bit representation directly.
math.h is part of the Standard C Library.
If you are interested in source code, the GNU C Library (glibc) is available to inspect.
EDIT TO ADD:
As others have said, math functions are typically implemented at the hardware level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With