基本数学的PHP浮点错误 [英] PHP floating point errors with basic Maths

查看:63
本文介绍了基本数学的PHP浮点错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么不能用二进制精确地表示十进制数字?
浮点值问题

Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?
problem with floating values

$var1 = 1;

for ( $i=0; $i<30; $i++ ) {
  $var1 += 0.1;
  $var2 = floor($var1);
  $var3 = $var1-$var2;
  if ( $var3 == 0.5 ) {
    $var1 = $var2+1;
  }
}

此循环的目的是先计数1.0、1.1、1.2、1.3、1.4,然后跳到2.0、2.1、2.2等

The intention of this loop is to count 1.0, 1.1, 1.2, 1.3, 1.4, and then jump to 2.0, 2.1, 2.2 etc

我遇到的问题是if语句从不正确.同样,每十分之一的计算都会得出一些疯狂的科学答案.

The problem I'm getting is that the if statement is never true. Also every tenth calculation resolves to some insane scientific answer.

我该如何解决?请帮忙!

How do I fix this? please help!

我匆匆忙忙地写了一个问题,现在已经不止一个了.

I wrote the question in a bit of a frustrated rush and it was more than one, I see that now.

问题的第一部分实际上是我如何绕过浮点运算来完成这项工作"和为什么还要进行该运算!"

The first part of the question really was "how can I make this work by-passing this floating point querk" and "why is this querk even happening!"

感谢您的所有宝贵答复,我投票的答案是正确的,很容易回答了核心问题如何完成这项工作".

Thank you for all the great replies and I'm voting the answer as correct that easily answered the core question of "how to make this work".

使用0.49而不是0.5,并使用>而不是==做到这一点.粗略的代码并不是世界上最好的代码,但它确实解决了原始问题.感谢大家提供的其他答复,我将继续阅读它们,并跟进以改进我的编码.

Using 0.49 instead of 0.5 and > instead of == does it. Crude and not the best code in the world but it does solve the original question. Thank you to everyone for the other responses that I am going to read and follow up on to improve my coding.

再次感谢.

推荐答案

此解决方案提供了所需的结果:

This one gives desired results:

$var1 = 1;
for ( $i=0; $i<30; $i++ ) {
    $var1 += 0.1;
    $var2 = (int)($var1);
    $var3 = $var1-$var2;
    if ( $var3 >= 0.45 ) {
        $var1 = $var2+1;
    }
    echo $var1.' '.$var2.' '.$var3.'<br/>';
}

这篇关于基本数学的PHP浮点错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆