Jen*_*nni 8 php floating-point numerical-methods
有没有办法在PHP中获取浮点数的二进制表示?像Java的Double.doubleToRawLongBits()之类的东西.
给定一个正浮点数,我想获得最大可表示的浮点数,该数字小于该数.在Java中,我可以这样做:
double x = Double.longBitsToDouble(Double.doubleToRawLongBits(d) - 1);
Run Code Online (Sandbox Code Playgroud)
但我在PHP中没有看到类似的东西.
这是我使用Peter Bailey的建议提出的解决方案。它需要 64 位版本的 PHP。我不以任何方式声称这具有生产质量,但我会分享以防万一有人想以此为基础。(事实上,我在发布问题后最终做了一些完全不同的事情,但我把它留在这里作为智力练习。)
// Returns the largest double-precision floating-point number which
// is less than the given value. Only works for positive values.
// Requires integers to be represented internally with 64 bits (on Linux
// this usually means you're on 64-bit OS with PHP built for 64-bit OS).
// Also requires 64-bit double-precision floating point numbers, but I
// think this is the case pretty much everywhere.
// Returns false on error.
function prevDouble($d) {
$INT32_MASK = 0xffffffff;
if((0x1deadbeef >> 32) !== 1) {
echo 'error: only works on 64-bit systems!';
return false;
}
if($d <= 0) {
return false;
}
$beTest = bin2hex(pack('d', 1.0)); //test for big-endian
if(strlen($beTest) != 16) {
echo 'error: system does not use 8 bytes for double precision!';
return false;
}
if($beTest == '3ff0000000000000') {
$isBE = true;
}
else if($beTest == '000000000000f03f') {
$isBE = false;
}
else {
echo 'error: could not determine endian mode!';
return false;
}
$bin = pack('d', $d);
//convert to 64-bit int
$int = 0;
for($i = 0; $i < 8; $i++)
$int = ($int << 8) | ord($bin[$isBE ? $i : 7 - $i]);
$int--;
//convert back to double
if($isBE)
$out = unpack('d', pack('N', ($int >> 32) & $INT32_MASK) . pack('N', $int & $INT32_MASK));
else
$out = unpack('d', pack('V', $int & $INT32_MASK) . pack('V', ($int >> 32) & $INT32_MASK));
return $out[1];
}
Run Code Online (Sandbox Code Playgroud)
作为不是对整个问题而是对标题的附加答案:
如果您想查看浮点数作为二进制文件的外观:
function floatToBinStr($value) {
$bin = '';
$packed = pack('d', $value); // use 'f' for 32 bit
foreach(str_split(strrev($packed)) as $char) {
$bin .= str_pad(decbin(ord($char)), 8, 0, STR_PAD_LEFT);
}
return $bin;
}
echo floatToBinStr(0.0000000000000000000000000000000000025).PHP_EOL;
echo floatToBinStr(0.25).PHP_EOL;
echo floatToBinStr(0.5).PHP_EOL;
echo floatToBinStr(-0.5).PHP_EOL;
Run Code Online (Sandbox Code Playgroud)
输出:
0011100010001010100101011010010110110111111110000111101000001111
0011111111010000000000000000000000000000000000000000000000000000
0011111111100000000000000000000000000000000000000000000000000000
1011111111100000000000000000000000000000000000000000000000000000
Run Code Online (Sandbox Code Playgroud)