473,573 Members | 3,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Check my math!

Someone please explain what alternate universe I fell into this
afternoon when PHP started telling me that 2 doesn't equal 2.

Not sure about you, but when I run this, it tells me 59001.31 doesn't
equal 59001.31. Change each side of the equation by a hundreth or two
and it checks. Change it a bit more, and it won't.

_What_ is going on here?!

<?php
$subtotal=59001 .31;
$principal=5860 5.33;
$interest=395.9 8;
$check=$princip al+$interest;
echo("<pre>");
echo("Check: " . $check . "\n");
echo("Subtotal: " . $subtotal . "\n");
if($check!=$sub total) {
echo("Check (" . $check . ") does not equal subtotal (" .
$subtotal . ")"); // Check doesn't equal subtotal
}
else {
echo("Check (" . $check . ") equals subtotal (" . $subtotal .
")"); // Check does equal subtotal
}
echo("</pre>");
?>

--
Craig Bailey, Communications Coordinator
Vermont Housing Finance Agency (VHFA)
164 St. Paul St., P.O. Box 408
Burlington, Vt. 05402-0408
Email: cb*****@vhfa.or g | Web: www.vhfa.org
Phone: (802) 652-3463 | Fax: (802) 864-5746
Jul 17 '05 #1
17 4165
Floating operations always introduces small errors, that's why. Run this and
you'll see:

<?php
$subtotal=59001 .31;
$principal=5860 5.33;
$interest=395.9 8;
$check=$princip al+$interest;
$diff=$check - $subtotal;
echo("<pre>");
echo("Check: " . $check . "\n");
echo("Subtotal: " . $subtotal . "\n");
if($check!=$sub total) {
echo("Check (" . $check . ") does not equal subtotal (" .
$subtotal . ")."); // Check doesn't equal subtotal
printf("Their difference is %01.40f", $diff);
}
else {
echo("Check (" . $check . ") equals subtotal (" . $subtotal .
")"); // Check does equal subtotal
}
echo("</pre>");
?>

The decimal part of a float is represented internally as a fraction of some
denominator that is of the power of 2. Decimals that are not
1/(2^n)therefore cannot be represented precisely.

59001.31 is 59001 + 5325759447 / 2^34 or
59001.309999999 997671693563461 3037109375
58605.33 is 58605 + 22677427323 / 2^36 or
58605.330000000 001746229827404 022216796875
395.98 is 395 + 2155042790441 / 2^41 or
395.98000000000 001818989403545 85647583007813

When you add up the fractions, lo and behold, they don't add up exactly (the
error is 1/(2^37)).

You should do what Mike suggested. Whenever you divide something or multiple
something by a floating point number, pass the result through round().

Uzytkownik "Craig Bailey" <cb*****@vhfa.o rg> napisal w wiadomosci
news:cb******** *************** ****@sover.net. client.newsread .com...
Someone please explain what alternate universe I fell into this
afternoon when PHP started telling me that 2 doesn't equal 2.

Not sure about you, but when I run this, it tells me 59001.31 doesn't
equal 59001.31. Change each side of the equation by a hundreth or two
and it checks. Change it a bit more, and it won't.

_What_ is going on here?!

<?php
$subtotal=59001 .31;
$principal=5860 5.33;
$interest=395.9 8;
$check=$princip al+$interest;
echo("<pre>");
echo("Check: " . $check . "\n");
echo("Subtotal: " . $subtotal . "\n");
if($check!=$sub total) {
echo("Check (" . $check . ") does not equal subtotal (" .
$subtotal . ")"); // Check doesn't equal subtotal
}
else {
echo("Check (" . $check . ") equals subtotal (" . $subtotal .
")"); // Check does equal subtotal
}
echo("</pre>");
?>

--
Craig Bailey, Communications Coordinator
Vermont Housing Finance Agency (VHFA)
164 St. Paul St., P.O. Box 408
Burlington, Vt. 05402-0408
Email: cb*****@vhfa.or g | Web: www.vhfa.org
Phone: (802) 652-3463 | Fax: (802) 864-5746

Jul 17 '05 #2

"Chung Leong" <ch***********@ hotmail.com> wrote
You should do what Mike suggested. Whenever you divide something or multiple something by a floating point number, pass the result through round().


LOL somebody here capable of programming? Just ironic, reading too much
bulls*** here.

What should somebody use floats for, when always rounding that shit before
doing mathematics?

If you have to use floats and need to to compare them, round them before
comparing. But when using floats that have to be compared, your concept is
broken.

Carl
Jul 17 '05 #3
In article <2O************ *****@newssvr27 .news.prodigy.c om>,
"CountScubu la" <me@scantek.hot mail.com> wrote:
I did not get into it, but just for a quick reference, when you deal with
money in software/scripts, it is best to convert over to cents, thus 395.98
is 39598, deal with all numbers as whole numbers, and when you go to print
it then add the decimal, the decimal is a human thing, for parts of a
dollar.


Thanks for all the help. Though I admit that I'm a little floored that a
scripting language doesn't have a more elegant way to handle something
like ... er ... _numbers_.

And here I thought computers were _good_ with numbers ...

--
Craig Bailey, Communications Coordinator
Vermont Housing Finance Agency (VHFA)
164 St. Paul St., P.O. Box 408
Burlington, Vt. 05402-0408
Email: cb*****@vhfa.or g | Web: www.vhfa.org
Phone: (802) 652-3463 | Fax: (802) 864-5746
Jul 17 '05 #4
On Tue, 13 Jan 2004 18:20:34 GMT, Craig Bailey <cb*****@vhfa.o rg> wrote:
In article <2O************ *****@newssvr27 .news.prodigy.c om>,
"CountScubu la" <me@scantek.hot mail.com> wrote:
I did not get into it, but just for a quick reference, when you deal with
money in software/scripts, it is best to convert over to cents, thus 395.98
is 39598, deal with all numbers as whole numbers, and when you go to print
it then add the decimal, the decimal is a human thing, for parts of a
dollar.


Thanks for all the help. Though I admit that I'm a little floored that a
scripting language doesn't have a more elegant way to handle something
like ... er ... _numbers_.

And here I thought computers were _good_ with numbers ...


They are. But there have to be compromises when storing floating point
numbers. For example, if you do 1.0/3.0, you get 0.33333 recurring. How do you
store an infinite number of decimal places in a (small) finite space?

There are floating point storage schemes that can represent recurring numbers
exactly, but they're relatively complicated. The IEEE format used by most
processors lets you store the number in a smallish space and have simpler
circuitry to process it, but the compromise is you lose accuracy after a
certain number of significant digits.

It's a hardware thing, not a language thing.

So, if you want exact maths on a computer, use integers, or find one of the
exact floating point maths libraries and put up with the performance penalties.

--
Andy Hassall <an**@andyh.co. uk> / Space: disk usage analysis tool
<http://www.andyh.co.uk > / <http://www.andyhsoftwa re.co.uk/space>
Jul 17 '05 #5
CountScubula wrote:
I did not get into it, but just for a quick reference, when you deal with
money in software/scripts, it is best to convert over to cents, thus
395.98 is 39598, deal with all numbers as whole numbers, and when you go
to print it then add the decimal, the decimal is a human thing, for parts
of a dollar.

just my 2 cents or ($.02)

--
Mike Bradley "Craig Bailey" <cb*****@vhfa.o rg> wrote in message
news:cb******** *************** ****@sover.net. client.newsread .com...
Someone please explain what alternate universe I fell into this
afternoon when PHP started telling me that 2 doesn't equal 2.

Not sure about you, but when I run this, it tells me 59001.31 doesn't
equal 59001.31. Change each side of the equation by a hundreth or two
and it checks. Change it a bit more, and it won't.

_What_ is going on here?!


Heheh - I remember them telling us that in my 1st year of computer science
:) I so rarely deal with currency stuff I'd almost forgotten! Thanks for
the reminder.

James
--
Fortune cookie says:
America has been discovered before, but it has always been hushed up.
- Oscar Wilde

Jul 17 '05 #6
"CountScubu la" <me@scantek.hot mail.com> schrieb im Newsbeitrag
news:2O******** *********@newss vr27.news.prodi gy.com...
I did not get into it, but just for a quick reference, when you deal with
money in software/scripts, it is best to convert over to cents, thus 395.98 is 39598, deal with all numbers as whole numbers, and when you go to print
it then add the decimal, the decimal is a human thing, for parts of a
dollar.


So when using signed 32 bit integer values (the only PHP knows) you have
2,000,000,000 Cent or better 20,000,000.00 $ to be the limit of economics.
PHP then starts converting values to FLOAT. So when handling huge values one
better doesn't compare without additional rounding.

Carl
Jul 17 '05 #7
In article <i4************ *************** *****@4ax.com>,
Andy Hassall <an**@andyh.co. uk> wrote:
But there have to be compromises when storing floating point
numbers. For example, if you do 1.0/3.0, you get 0.33333 recurring. How do
you
store an infinite number of decimal places in a (small) finite space?


But that's not what I'm doing. I'm doing addition. I'm taking 10.25 and
adding it to 11.4.

Why can't the computer recognize that as 21.65?

If $total=21.65 and I compare that to 10.25+11.4, the fact that the
computer might not be able to recognize a match perplexs me.

I set $total=21.65 and ask it to print $total. It prints 21.65.

I set $anotherTotal=1 0.25+11.4. I ask it to print $anotherTotal. It
prints 21.65.

_Then_ I ask it if $total equals $anotherTotal and is says "No."

Huh?

--
Floydian Slip(tm) - "Broadcasti ng from the dark side of the moon"
Random Precision Productions(tm)
67 Union St. #2D, Winooski, Vt. 05404-1948 USA
Sundays, 7-8 pm - Champ 101.3 FM, Colchester; 102.1 FM, Randolph, Vt.
cc*@floydiansli p.com - AIM: RandomPrec - www.floydianslip.com
Jul 17 '05 #8
Mike's suggestion was to use fixed point math. Read the post, pal.

Uzytkownik "Carl Melot" <ca*****@linkwa ve.org> napisal w wiadomosci
news:bu******** *****@news.t-online.com...
What should somebody use floats for, when always rounding that shit before
doing mathematics?

If you have to use floats and need to to compare them, round them before
comparing. But when using floats that have to be compared, your concept is
broken.

Carl

Jul 17 '05 #9
On Wed, 14 Jan 2004 00:31:57 GMT, Craig Bailey <cc*@floydiansl ip.com> wrote:
In article <i4************ *************** *****@4ax.com>,
Andy Hassall <an**@andyh.co. uk> wrote:
But there have to be compromises when storing floating point
numbers. For example, if you do 1.0/3.0, you get 0.33333 recurring. How do
you
store an infinite number of decimal places in a (small) finite space?


But that's not what I'm doing. I'm doing addition. I'm taking 10.25 and
adding it to 11.4.

Why can't the computer recognize that as 21.65?

If $total=21.65 and I compare that to 10.25+11.4, the fact that the
computer might not be able to recognize a match perplexs me.

I set $total=21.65 and ask it to print $total. It prints 21.65.

I set $anotherTotal=1 0.25+11.4. I ask it to print $anotherTotal. It
prints 21.65.

_Then_ I ask it if $total equals $anotherTotal and is says "No."


For really gory details into Why, search for 'IEEE floating point
representation' . For example:

http://www.math.grin.edu/~stone/cour...EEE-reals.html

Since the system is based on binary powers, the inaccuracies don't come in
places that you might think if you're thinking in decimal. Various floating
point numbers that have an exact decimal representation end up as recurring
binary representation in the IEEE scheme, so get approximated. Taking the
numbers you pointed out:

<pre>
<?php
$x = 10.25;
$y = 11.4;

printf("x = %10.32f\n", $x);
printf("y = %10.32f\n", $y);
printf("x + y = %10.32f\n", $x+$y);
?>
</pre>

Outputs:

x = 10.250000000000 000000000000000 00000
y = 11.400000000000 000355271367880 05009
x + y = 21.649999999999 998578914528479 79963

I really can't remember the exact details of the IEEE representation any more,
I think like most people I just accept there are inaccuracies and so you
arrange code to expect them, and to minimise the number of repeated operations
(the more you do, the more inaccurate you get).

But from the above, you can see that 10.25 can be exactly represented, but
whilst it's got pretty close to 11.4, it's very slightly off. And again with
the sum of the two, it's slightly off.

With the IEEE representation, there is a (very small) value 'epsilon' which is
a limit of the inaccuracy between the number you want and the stored
representation of it. Check Google, and computer architecture books for the
boring but useful explanation of how it works.

--
Andy Hassall <an**@andyh.co. uk> / Space: disk usage analysis tool
<http://www.andyh.co.uk > / <http://www.andyhsoftwa re.co.uk/space>
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2284
by: Jussi Mononen | last post by:
Hi, I'm having problems to successfully execute the test scripts on a Compaq host ( OSF1 tr51bdev V5.1 2650 alpha ). Almost all tests end up with the following error message "PARI: *** Invalid arguments to divll. at test_eng/Testout.pm line 30. ...propagated at t/polyser.t line 9. t/polyser.....dubious
3
13697
by: Tony | last post by:
On PageA I have: <Input Type="CheckBox" Name="chkBox" Size="1" Value="True" checked> Which works fine! On PageB I have; <%If Request("chkBox")=True Then Response.Write "True" Else
17
3600
by: cwdjrxyz | last post by:
Javascript has a very small math function list. However there is no reason that this list can not be extended greatly. Speed is not an issue, unless you nest complicated calculations several levels deep. In that case you need much more ram than a PC has to store functions calculated in loops so that you do not have to recalculate every time...
8
39195
by: Eps | last post by:
I have a for loop and i want to do different things depending on whether the counter is even or odd. I know there is probably some really simple math thing that can do this but my maths is a bit hazy. I did check the MS C# library site but had no luck. Any help appreciated. --
11
7339
by: Sambo | last post by:
I have the following module: ------------------------------- import math def ac_add_a_ph( amp1, ph1, amp2, ph2 ): amp3 = 0.0 ph3 = 0.0 ac1 = ( 0, 0j ) ac2 = ( 0, 0j )
5
1548
by: Paolo | last post by:
Hi all! I have to create an application that receive some packet from an interface and builds a file from those. In the header there are three fields: one is the total lenght of the file, one is the offset of the packet in the file and one is the lenght of the current packet. I made a function that gets all the packets and reconstruct the...
0
1962
by: kirby.urner | last post by:
Cyber-curricula have a leveling aspect, as kids nearer Katrina's epicenter tune in and bliss out on 'Warriors of the Net' (why wait for stupid big dummy textbooks to catch up?). They feel more empowered by Python and Ubuntu than by any King's English I'd warrant, given how the latter has been dumbed down (slowed, degraded) by unimaginative...
10
11586
by: Joseph Geretz | last post by:
I need to calculate miles per degree longitude, which obviously depends on latitude since lines of longitude converge at the poles. Via Google, I've come up with the following calculation: private const double MilesPerDegLat = 69.04; private const double EarthRadiusMiles = 3963.1676; private static double PiDiv180 = Math.PI / 180; double...
4
1306
by: davidson1 | last post by:
Hai Friends, I have a javascript program , as a snow a single picture will fall from above to below in the browser.It is worked properly when my friend was using.Sudennly it is not working ,pl correct if there is any error and send me............... <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript">
0
7641
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7705
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5248
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3685
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2145
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1241
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.