PHP 8.5.0 Beta 1 available for testing

Voting

: nine minus one?
(Example: nine)

The Note You're Voting On

zooly at globmi dot com
14 years ago
PHP does not have the following math function in any extensions:

frexp() - Extract Mantissa and Exponent of the Floating-Point Value

I've digged many C source codes, and found the simplest implementation as follows:

<?php

function frexp ( $float ) {

$exponent = ( floor(log($float, 2)) + 1 );
$mantissa = ( $float * pow(2, -$exponent) );

return(
array(
$mantissa, $exponent)
);

}

print_r(frexp(0.0345));
print_r(frexp(21.539));

?>

Array
(
[0] => 0.552
[1] => -4
)
Array
(
[0] => 0.67309375
[1] => 5
)

I have compared the results using a lot of floats against C's frexp function - they are the same.

Note that C and PHP uses different float precisions, for example "4619.3" gives:

C: 0.56387939453125, 13
PHP: 0.563879394531, 13

/Assuming default configurations./

<< Back to user notes page

To Top