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.98999999999 999998" 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)) 5 2931
Vio fed this fish to the penguins on Friday 07 November 2003 05:34 am: Perhaps because Python translates "25.99" to "25.98999999999 999998" 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.989999999999 998 a
25.990000000000 002
-- =============== =============== =============== =============== == < wl*****@ix.netc om.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/ <
Vio <vm*******@symp atico.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.
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/>
"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*********@cc raig.org>
"The mistakes made by Congress wouldn't be so bad if the next Congress
didn't keep trying to correct them." Cullen Hightower
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.
"Christophe r A. Craig" <li*********@cc raig.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*********@cc raig.org> "The mistakes made by Congress wouldn't be so bad if the next Congress didn't keep trying to correct them." Cullen Hightower
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 I have to make it decimal before
calculating, but I am not sure about it. Any light upon this simple (or it
seems to me so, at least) begginner problem?
TIA..
|
by: Rene |
last post by:
The following code:
float someFloat = 0;
for(int x = 1; x <= 10; x++)
{
someFloat += .1F;
Console.WriteLine(someFloat.ToString());
}
|
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) the program goes haywire (the main repeats over and over again).
Is there a way to limit the user in entering only numbers, not letters or characters? Here is the code:
// Interest calculator, by Bl00dFox
#include <iostream>
|
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 below? I would appreciate
if you can share your experience using such a structure. Thanks.
std::map<float, intm;
JD
|
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!
| |
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 multiple it by 1000 to
get 11111 and the preform bitwise like <<2 to get 88888 and then divide
by 1000 to go back to float 8.8888. but these seem like "nasty" way to
do it. So maybe some of you have great tips?
Thank you in advance!
L R
|
by: crybaby |
last post by:
import re
s1 =' 25000 '
s2 = ' 5.5910 '
mypat = re.compile('*(\.*|$)')
rate= mypat.search(s1)
print rate.group()
rate=mypat.search(s2)
|
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 value entered and min value entered. the min is where i am having a problem i can get everything else to print out but i am doing something wrong in my while loop can someone please help me.
import javax.swing.*; // gets option pane
...
|
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 amount as 2.3841858e-007 instead of 0.00000024
|
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 cropped up before, since
I rarely use "float"s for anything, and hardly ever use the function for
floating-point numbers in the first place; I just was messing around
testing it for all cases and noticed a problem.)
Anyway, it is declared and I...
|
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |