Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

floating point precision - PHP - Getting a float variable internal value

I am trying to establish the delta I need when doing float comparison in PHP. I want to take a closer look at my variables to see the difference.

I have 2 computed variables, $a, $b.

$a = some_function();

$b = some_other_function();

How can I see the exact number which PHP uses?

I want to compare them with this formula, where I need to specify the delta:

$delta = 0.00001;
if (abs($a-$b) < $delta) {
  echo "identical";
}

var_dump($a, $b) returns 1.6215; 1.6215. but I know that they are not exactly equal because

var_dump($a === $b);

evaluates to false;

Why doesn't var_dump() print the internal value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In PHP, the printed values of floating point numbers are dependent on PHP configuration "precision".

You can change that with:

ini_set('precision', YOUR_DESIRED_PRECISION_AS_INTEGER);

For example with with:

ini_set('precision', 18);

Your numbers may display something like:

float 1.62149999999999994

float 1.6214999999999995

So now the difference between them is clearer.

So your delta may be: $delta = 0.00000000000001; It really depends of the precision you are looking for.

If you need to do exact mathematical calculations, do have a look at the BC Math Functions.


References / Sources

PHP - Floating point numbers

PHP - Floating point numbers - User Contributed Notes - deminy at deminy dot net

Codepad


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...