Heim  >  Artikel  >  Backend-Entwicklung  >  数据结构 - 关于PHP浮点数精度问题

数据结构 - 关于PHP浮点数精度问题

WBOY
WBOYOriginal
2016-06-06 20:41:09938Durchsuche

PHP manual中说:

以十进制能够精确表示的有理数如 0.1 或 0.7,无论有多少尾数都不能被内部所使用的二进制精确表示,因此不能在不丢失一点点精度的情况下转换为二进制的格式。

<code>// example1
$float = (0.1 + 0.7) * 10;
echo (integer) $float;            // 7
echo floor($float);               // 7

// example2
echo (integer) (1.5+1.5);         // 3
echo floor(1.5+1.5);              // 3

// example3
echo (integer) (0.5*10);          // 5
echo floor(0.5*10);               // 5
</code>

为什么在例子2和例子3中,浮点数的运算能够保全精度呢?

回复内容:

PHP manual中说:

以十进制能够精确表示的有理数如 0.1 或 0.7,无论有多少尾数都不能被内部所使用的二进制精确表示,因此不能在不丢失一点点精度的情况下转换为二进制的格式。

<code>// example1
$float = (0.1 + 0.7) * 10;
echo (integer) $float;            // 7
echo floor($float);               // 7

// example2
echo (integer) (1.5+1.5);         // 3
echo floor(1.5+1.5);              // 3

// example3
echo (integer) (0.5*10);          // 5
echo floor(0.5*10);               // 5
</code>

为什么在例子2和例子3中,浮点数的运算能够保全精度呢?

又是献上我博客的时候了:

  • 代码之谜(四)- 浮点数(从惊讶到思考)
  • 代码之谜(五)- 浮点数(谁偷了你的精度?)

0.1 + 0.7 的结果是 0.7999999999999999

0.5 1.5 可以用浮点数精确的表示。

0.1 的二进制:

<code>符号位 0 
指数 01111011 (-4)
位数 1.10011001100110011001101 (1.60000002384185791015625)
</code>

将这个数在转回十进制:0.10000000149011612

0.7 的二进制:

<code>符号位 0 
指数 01111110  (-1)
位数 1.01100110011001100110011 (1.39999997615814208984375)
</code>

将这个数在转回十进制:0.699999988079071

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn