Security advisory: Critical remote code execution vulnerabilities, update now

fdiv

(PHP 8)

fdiv — Divides two numbers, according to IEEE 754

说明

function fdiv(float $num1, float $num2): float

Returns the floating point result of dividing the num1 by the num2. If the num2 is zero, then one of INF, -INF, or NAN will be returned.

Note that in comparisons, NAN will never be equal (==) or identical (===) to any value, including itself.

参数

num1

The dividend (numerator)

num2

The divisor

返回值

The floating point result of num1/num2

示例

示例 #1 Using fdiv()

<?php
var_dump(fdiv(5.7, 1.3)); // float(4.384615384615385)
var_dump(fdiv(4, 2)); // float(2)
var_dump(fdiv(1.0, 0.0)); // float(INF)
var_dump(fdiv(-1.0, 0.0)); // float(-INF)
var_dump(fdiv(0.0, 0.0)); // float(NAN)
?>

参见

  • Division operator /
  • intdiv() - 对除法结果取整 - Integer division
  • fmod() - 返回除法的浮点数余数
  • fpow() - Raise one number to the power of another, according to IEEE 754

+添加备注

用户贡献的备注 2 notes

up
2
rmaslo at post dot cz
9 months ago
Subject: Compatibility for older PHP

Text: Equivalent for versions before 8.0. Handles the sign of zero for INF results.

<?php
if (!function_exists('fdiv')) {
    function fdiv(float $a, float $b): float
    {
        if (is_nan($a) || is_nan($b)) return NAN;
        if ($b != 0.0) return $a / $b;
        if ($a == 0.0) return NAN;

        $check = function ($v) {
            if ($v > 0) return 1;
            if ($v < 0) return -1;
            return pack('d', (float)$v) === pack('d', 0.0) ? 1 : -1;
        };

        return ($check($a) === $check($b)) ? INF : -INF;
    }
}
?>
up
0
biziclop at example dot com
5 days ago
A shorter compatibility version, works from PH5.3+:
<?php
if( ! function_exists('fdiv')){
  function fdiv( $a, $b ){
    if( $b )  return $a / $b;  // b: nonzero / ±INF / NAN
    if( ! $a || is_nan( $a ))  return NAN;  // 0/0, NAN/0
    return atan2( $b / $a, -1.0 ) > 0 ? INF : -INF;  // b:±0, a: nonzero / ±INF
  }
}
?>

A small test, should print nothing:
<?php
function fdiv2( $a, $b ){
  if( $b )  return $a / $b;
  if( ! $a || is_nan( $a ))  return NAN;
  return atan2( $b / $a, -1.0 ) > 0 ? INF : -INF;
}
$vals = array( +1.0, -1.0, +0.0, -1*0.0, +INF, -INF, 1E308, -1E308, 1E-323, -1E-323, NAN );
function float2bin( $f ){  return is_nan( $f ) ? 'NAN' : pack('d', $f );  }
foreach( $vals as $a )  foreach( $vals as $b ){
  $r1 = fdiv(  $a, $b );
  $r2 = fdiv2( $a, $b );
  if( float2bin( $r1 ) !== float2bin( $r2 ))  print_r('', $a, $b, $r1, $r2 );
}
?>
To Top