473,233 Members | 1,753 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,233 software developers and data experts.

simple float numbers problem

Vio
I need to test for equality between simple 2 decimal numbers. For example:

if (10 + 15.99) == 25.99:
do some stuff...

The preceding sentence should be TRUE, but to Python it appears FALSE.
Which is wrong.

Perhaps because Python translates "25.99" to "25.98999999999999998" and
not "25.99", which may be the reason for this error (me guessing...). If
that's the case, how do I force Python to only use 2 decimal points, and
not "make up" superfluous decimals? Or if that's not the cause for the
problem, how do I make Python see my math expression as TRUE (as it
"should" be)?

Cheers,
Vio

PS. If it's of any help, I'm using Python2.3 (GCC 2.95.4 20011002
(Debian prerelease))

Jul 18 '05 #1
5 2910
Vio fed this fish to the penguins on Friday 07 November 2003 05:34 am:

Perhaps because Python translates "25.99" to "25.98999999999999998"
and not "25.99", which may be the reason for this error (me
guessing...). If that's the case, how do I force Python to only use 2
decimal points, and not "make up" superfluous decimals? Or if that's
not the cause for the problem, how do I make Python see my math
expression as TRUE (as it "should" be)?
You don't... Computer floating point arithmetic is not precise. {I
seem to have misplaced my copy, but there is a book with a title
something like "Real Math Made Real" that discusses this}

The recommendation from my old computer classes is that you never test
floats for equality -- you test the difference between floats against
some acceptable error limit.

epsilon = 0.0000001
if abs( (10 + 15.99) - 25.99) < epsilon:
# considered equal

-=-=-=-=-=-=-
Python 2.2 (#1, Nov 5 2002, 15:43:24)
[GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386
Type "help", "copyright", "credits" or "license" for more information.
epsilon = 0.0000001
a = 10 + 15.99
if abs(a - 25.99) < epsilon: .... print a, " is equal to ", 25.99
....
25.99 is equal to 25.99 print a 25.99 print 25.99 25.99 25.99 25.989999999999998 a 25.990000000000002


-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Bestiaria Home Page: http://www.beastie.dm.net/ <
Home Page: http://www.dm.net/~wulfraed/ <


Jul 18 '05 #2
Vio <vm*******@sympatico.ca> wrote:

I need to test for equality between simple 2 decimal numbers. For example:

if (10 + 15.99) == 25.99:
do some stuff...

The preceding sentence should be TRUE, but to Python it appears FALSE.
Which is wrong.
And the same thing would happen if you wrote the same sentence in C. The
problem is that 15.99 in binary is an infinitely repeating decimal. It
cannot be represented exactly.
If that's the case, how do I force Python to only use 2 decimal points,
and not "make up" superfluous decimals?
There are two good solutions. One, as others have suggested, is to store
everything in units of cents. Your expression becomes:

if 1000 + 1599 == 2599:
do some stuff...

All you need to do is translate when you do input and output. This is the
approach Visual Basic takes with its Currency data type (although it
actually multiples by 1000, not 100).

Another solution is to use a "CloseTo" function to do the comparison:

def CloseTo(x,y):
return abs(x-y) < 0.005

if (10.00 + 15.99, 25.99):
do some thuff...
Or if that's not the cause for the problem, how do I make
Python see my math expression as TRUE (as it "should" be)?


In a binary computer, your statement is false. Just that simple. You need
to find a way to express your statement in a way that produces the results
you want.
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 18 '05 #3
On Sun, 09 Nov 2003 00:10:14 -0800, Tim Roberts wrote:
Another solution is to use a "CloseTo" function to do the comparison:

def CloseTo(x,y):
return abs(x-y) < 0.005


A modified CloseTo() that allows a varying epsilon:

def CloseTo( x, y, epsilon=0.005 ):
return ( abs( x - y ) < epsilon )

--
\ "During the Middle Ages, probably one of the biggest mistakes |
`\ was not putting on your armor because you were 'just going down |
_o__) to the corner.'" -- Jack Handey |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #4
"Ladvánszky Károly" <aa@bb.cc> writes:
Lisp does the right thing:
(= (+ 10 15.99) 25.99)
T

Does Lisp not use the math processor?


I don't know which Lisp you're speaking of here, but chances are very
good that 15.99 is not a float in this particular lisp. I'd guess
it's probably rational. You can do that with Python if you get a
rational library such as the one I mentioned in my previous post to
this thread. The problem is that rationals are notoriously slow. If
you tried to implement

a = 0
for i in range(1,5000):
a += 1./i

in this lisp, and I'm right, it should take longer than Python (but
will give the "right" answer instead of Python's approximate one)

--
Christopher A. Craig <li*********@ccraig.org>
"The mistakes made by Congress wouldn't be so bad if the next Congress
didn't keep trying to correct them." Cullen Hightower
Jul 18 '05 #5
I'm running CLISP.
(type-of 25.99) gives SINGLE-FLOAT
(type-of (+ 10 15.99)) gives SINGLE-FLOAT
I'm going to post it on the List group to see what Lispers say about it.
By the way, Smalltalk also gives the right answer.

"Christopher A. Craig" <li*********@ccraig.org> az alábbiakat írta a
következo hírüzenetben: ma************************************@python.org...
"Ladvánszky Károly" <aa@bb.cc> writes:
Lisp does the right thing:
(= (+ 10 15.99) 25.99)
T

Does Lisp not use the math processor?


I don't know which Lisp you're speaking of here, but chances are very
good that 15.99 is not a float in this particular lisp. I'd guess
it's probably rational. You can do that with Python if you get a
rational library such as the one I mentioned in my previous post to
this thread. The problem is that rationals are notoriously slow. If
you tried to implement

a = 0
for i in range(1,5000):
a += 1./i

in this lisp, and I'm right, it should take longer than Python (but
will give the "right" answer instead of Python's approximate one)

--
Christopher A. Craig <li*********@ccraig.org>
"The mistakes made by Congress wouldn't be so bad if the next Congress
didn't keep trying to correct them." Cullen Hightower

Jul 18 '05 #6

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

Similar topics

5
by: Yodai | last post by:
Hi all! I have an int that comes with a value like 0x07fa and I have to turn it into a float value of 204.2 decimal to display it.... if I try to divide it by 10 I get bogus numbers. I presume...
8
by: Rene | last post by:
The following code: float someFloat = 0; for(int x = 1; x <= 10; x++) { someFloat += .1F; Console.WriteLine(someFloat.ToString()); }
1
by: Bl00dFox | last post by:
Hi I am making a simple program to calculate interest. At the beginning when the user has to pick 1 or 2 (to select simple or compound interest respectively), if the user enters a letter (eg, a)...
23
by: JDT | last post by:
Hi, It seems that using floats as the first tupelo for an STL map (shown below) can cause problems but I don't remember what the problems were. Is it common practice to use a structure like...
8
by: buzzweetman | last post by:
Can someone explain this: void Test() { short x = 10; float y = 9.9f; float a = (float)x; a *= y; short b = (short)a; // I get 99. Good!
45
by: Carramba | last post by:
Hi! I now that I can't do straight forward any bitwise operation on float (double etc..). But I wondering what is the easiest/best way to do this? I was thinking if I have float x=1.1111 so I can...
3
by: crybaby | last post by:
import re s1 ='&nbsp;25000&nbsp;' s2 = '&nbsp;5.5910&nbsp;' mypat = re.compile('*(\.*|$)') rate= mypat.search(s1) print rate.group() rate=mypat.search(s2)
3
by: powerej | last post by:
writing a program that asks how many numbers the users want to enter, then input an integer for the amount of numbers said, output: number of integers entered, sum of them, average of them, maximum...
5
by: Selvam | last post by:
Hi All, I am getting exponent value when doing float arithmetic in C++. Instead of that I need accurate value. float amount = 0.0f; float x = 0.99999976f; amount= 1.0f - x; I am getting...
22
by: Bill Reid | last post by:
I just noticed that my "improved" version of sscanf() doesn't assign floating point numbers properly if the variable assigned to is declared as a "float" rather than a "double". (This never...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.