gpt4 book ai didi

php - 为什么 float != float

转载 作者:行者123 更新时间:2023-12-02 15:38:41 24 4
gpt4 key购买 nike

$a     = 100;
$b = 3;
$test1 = $a/ $b;
$test2 = 33.333333333333; // $test2 == $test1

var_dump(($test1 * $b)); // float(100)
var_dump(($test2 * $b)); // float(99.999999999999)

有什么解释吗?

最佳答案

100/3 导致 33.3-repeating

没有小数点值会显示它。在数学中,这样的数字通常由重复值上的一个小点表示。 (尽管我不知道如何在此代码框中显示)。

引用这个wiki article查看它们在不同地方的表示方式以及我在此处给出的更详细的解释。

但是,这里是这篇文章的摘要片段:

In arithmetic, repeating decimal is a way of representing a rational number. Thus, a decimal representation of a number is called a repeating decimal (or recurring decimal) if at some point it becomes periodic, that is, if there is some finite sequence of digits that is repeated indefinitely. For example, the decimal representation of 1/3 = 0.3333333… or 0.3 (spoken as "0.3 repeating", or "0.3 recurring") becomes periodic just after the decimal point, repeating the single-digit sequence "3" infinitely. A somewhat more complicated example is 3227/555 = 5.8144144144…, where the decimal representation becomes periodic at the second digit after the decimal point, repeating the sequence of digits "144" indefinitely.

现在,这是您问题的症结所在,但也请记住(正如其他两个答案所指出的那样) float 在计算和比较方面非常天真。快速搜索该站点会发现一小群人对 float 的内部表示有问题 - 主要是在进行比较时导致意外行为。

仔细阅读 float data type 上的 PHP 警告- 我再次在这里复制了重要的部分:

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

关于php - 为什么 float != float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12635354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com