Re: sprintf() oddness

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



At 7:10 AM -0500 12/1/07, Christoph Boget wrote:
Why does

sprintf( '%.03f', 0.15250000 )

return 0.152 while

sprintf( '%.03f', 0.15750000 )

return 0.158?

The 4th significant digit in both cases is '5' but in the first case, it's
rounded down but in the second case it is rounded up.  Is sprintf() basing
it's decision on the value of the 3rd significant digit?  If so, why?
Shouldn't rounding decisions be based on subsequent digits and not preceding
ones?

I am using PHP 4.3.11

thnx,
Christoph


Actually, it's more accurate to use the preceding digit to determine rounding. What you describe is "if even then round down else round up". That's more accurate than always rounding up or always rounding down.

Please follow:

When the digit is zero, no rounding takes place.
When the digit is 1 - 4, round down.
When the digit is 6 - 9, round up.

Fine up to there -- but, if you always round up or down for 5, then you are introducing bias.

So, if you use the even/odd value of the preceding digit to determine which way to round for 5, then it's more accurate.

However, no rounding is accurate -- it's just that some methods are less error prone.

Here's a demo:

http://www.webbytedd.com/bbb/rounding/

My rounding method doesn't always win against php's round(), but it wins more times than not. Plus, it takes a lot of rounding to introduce the bias I found and thus for most applications using the round() function (always round down) will suffice.

Cheers,

tedd

--
-------
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux