473,569 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing double in for loop

Hi all,

i have encountered the strangest behavior. Check out this simple
program:

#include <stdio.h>

int main()
{
double time = 1;
double i = 0;

for (double i = 0; i < time ; i+=0.01 )
{
if ( i == 0.15 )
{
printf( "found %f\n", i);
}
if ( i < 0.1 )
{
printf( "foundXX %f\n", i);
}
}

return 1;
}

What would you expect to be printed:
All the numbers from 0.0 to 0.9 with the prefex: foundXX
and last line in output should be found 0.15 - right?!
Wrong... what I get is all the numbers from 0.0 to 0.1 printed
(including 0.1!!)
When checking if ( i==0.1) { printf( "foundXX %f\n",i);} it does not
print foundXX 0.1!!
Why exactly does it think that 0.1 is < than 0.1!!??

anyone?

Thanks
Apr 9 '08 #1
18 2874
em************@ gmail.com writes:
>Hi all,
>i have encountered the strangest behavior.
See
http://www.eason.com/library/math/floatingmath.pdf
or (easier and more appropriate for your problem)
http://www.mathworks.com/company/new...all96Cleve.pdf
Apr 9 '08 #2
Tim Love wrote:
http://www.eason.com/library/math/floatingmath.pdf
or (easier and more appropriate for your problem)
http://www.mathworks.com/company/new...all96Cleve.pdf
Good reading material. For a quick answer:

http://www.parashift.com/c++-faq-lit...html#faq-29.17
Apr 9 '08 #3
em************@ gmail.com wrote:
for (double i = 0; i < time ; i+=0.01 )
{
if ( i == 0.15 )
{
printf( "found %f\n", i);
}
if ( i < 0.1 )
{
printf( "foundXX %f\n", i);
}
}
As others have pointed out, 0.01 cannot be represented accurately with
floating point numbers (for the same reason as eg. 1/3 cannot be
represented accurately with decimal numbers).

Clearly you want a precise number of iterations to your loop, and you
want precise control on what happens with some precise values of the
loop counter. In those cases what you should do is to use an integer
loop counter, and calculate the floating point value from it. In other
words:

for(int i = 0; i < 100; ++i)
{
double value = i/100.0;

if(i == 15) std::cout << "found " << value << "\n";
if(i < 10) std::cout << "foundXX " << value << "\n";
}

The integer loop counter will make sure that an accurate number of
iterations is performed, and comparing this integer loop counter in the
conditionals will make sure that those conditionals give an accurate
result. Whenever the floating-point value needs to be used, use the
'value' variable, as exemplified above.
Apr 9 '08 #4
Mi************* **@gmail.com wrote:
Machine double numbers are a finite subset of the
infinite real number domain. The operations on them executed by a
computer are similar but not identical to the math +, -, *, /, ...
operators 0.1 + 0.1 + 0.1 + 0.1 + 0.1 .

Then why doesn't an implementation use a large number of bits, for
people that want accuracy and also for x==y to work?
Like 8,000 bits or 8,000,000 bits or any number of bits necessary to
store all the possible numbers for double for example.
Apr 9 '08 #5
"Ioannis Vranos" <iv*****@nospam .no.spamfreemai l.grwrote in message
news:ft******** ***@ulysses.noc .ntua.gr...
Mi************* **@gmail.com wrote:
>Machine double numbers are a finite subset of the
infinite real number domain. The operations on them executed by a
computer are similar but not identical to the math +, -, *, /, ...
operators 0.1 + 0.1 + 0.1 + 0.1 + 0.1 .


Then why doesn't an implementation use a large number of bits, for
people that want accuracy and also for x==y to work?
Like 8,000 bits or 8,000,000 bits or any number of bits necessary to
store all the possible numbers for double for example.
Since 0.1 in binary is an infinate regression, it would take an infinite
number of bits to represent it.

--
Jim Langston
ta*******@rocke tmail.com
Apr 10 '08 #6
Ioannis Vranos wrote:
Then why doesn't an implementation use a large number of bits, for
people that want accuracy and also for x==y to work?
Sure, if you want your program to be a thousand times slower.

The C++ compiler will usually use the FPU (and sometimes even SSE) to
make floating point calculations in hardware. To get larger floating
point values you would have to use a software library, which would be
enormously slower.

Besides, 0.1 is inaccurate in binary floating point format regardless
of the number of bits used (for the exact same reason as 1/3 is
inaccurate in decimal format regardless of how many decimals you use).
Like 8,000 bits or 8,000,000 bits or any number of bits necessary to
store all the possible numbers for double for example.
double already stores all possible numbers representable with a double.
Apr 10 '08 #7
On 10 Apr., 01:49, Ioannis Vranos <ivra...@nospam .no.spamfreemai l.gr>
wrote:
Michael.Boehni. ..@gmail.com wrote:
Machine double numbers are a finite subset of the
infinite real number domain. The operations on them executed by a
computer are similar but not identical to the math +, -, *, /, ...
operators 0.1 + 0.1 + 0.1 + 0.1 + 0.1 .
oops. " != 0.5 " is missing.
>
Then why doesn't an implementation use a large number of bits, for
people that want accuracy and also for x==y to work?

Like 8,000 bits or 8,000,000 bits or any number of bits necessary to
store all the possible numbers for double for example.
A large number of bits is not enough, you'd need an *inifinte* number
of bits. Even if you extend the "normal" double numbers concept by
fractions (e.g. store two integer numbers 1 and 10 to represent 1/10),
you cannot represent the whole rational set (e.g. sqrt(2), pi or e
cannot be stored like this without loss of precision). Also, there is
an issue in performance: the more memory you use to store a single
value, the longer it will take to operate on them.

AFAIR, the current implementation by x86 CPUs uses 80 binary digits
for an extended precision floating point number internally and 64
binary digits to store a double in RAM memory. Should be enough for
most applications, *if* you follow the caveats mentioned before. -
Especially do not compare floats/doubles for (in)equality by != / ==
operators. If you want more precision you need to do it by application
code. This is considerably slower than using direct CPU/FPU commands
for floating point.

best,
Michael.
Apr 10 '08 #8
On Apr 10, 1:49 am, Ioannis Vranos <ivra...@nospam .no.spamfreemai l.gr>
wrote:
Michael.Boehni. ..@gmail.com wrote:
Machine double numbers are a finite subset of the
infinite real number domain. The operations on them executed by a
computer are similar but not identical to the math +, -, *, /, ...
operators 0.1 + 0.1 + 0.1 + 0.1 + 0.1 .
Then why doesn't an implementation use a large number of bits, for
people that want accuracy and also for x==y to work?
Like 8,000 bits or 8,000,000 bits or any number of bits
necessary to store all the possible numbers for double for
example.
I'm not sure I understand. A double has enough bits to store
all possible numbers for double. By definition---if the number
can't be stored in a double, then it's not a possible number for
double.

The problem here is that the real number 0.1 is not a possible
number for double. And if you're asking that the implementation
use enough bits to store all possible real numbers, that's
lg2(N), where N is the number of possible real numbers. And off
hand, how many possible real numbers would you say there are?

In this particular case, an implementation could have masked the
problem by using a decimal representation for double. But that
will fail as soon as you try something like:

step = 1.0/3.0 ;
for ( value = 0.0 ; value != 1.0 ; value += step ) ...

(Back when I was working in this environment, I actually wrote a
proof that for all finite representations of floating point
values, the loop:

step = 1.0/N ;
for ( value = 0.0 ; value != 1.0 ; value += step )

will fail for some values of N.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Apr 10 '08 #9
Juha Nieminen wrote:
Ioannis Vranos wrote:
>Then why doesn't an implementation use a large number of bits, for
people that want accuracy and also for x==y to work?

Sure, if you want your program to be a thousand times slower.

The C++ compiler will usually use the FPU (and sometimes even SSE) to
make floating point calculations in hardware. To get larger floating
point values you would have to use a software library, which would be
enormously slower.

Besides, 0.1 is inaccurate in binary floating point format regardless
of the number of bits used (for the exact same reason as 1/3 is
inaccurate in decimal format regardless of how many decimals you use).

OK, but in math we have a symbol to represent the infinite repeating
sequences in decimals, like 7.33333... or 7.343434...
Apr 10 '08 #10

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

Similar topics

11
2371
by: John | last post by:
Hi, I encountered a strange problem while debugging C code for a Windows-based application in LabWindows CVI V5.5, which led me to write the test code below. I tried this code with a different compiler and got the same erroneous result on two different PCs (with OS Win98 & Win98SE), so it appears to be a problem with ANSI C. I thought that...
88
21965
by: William Krick | last post by:
I'm currently evaluating two implementations of a case insensitive string comparison function to replace the non-ANSI stricmp(). Both of the implementations below seem to work fine but I'm wondering if one is better than the other or if there is some sort of hybrid of the two that would be superior. IMPLEMENTATION 1: #ifndef...
7
2225
by: Brian | last post by:
Hi, I have been trying to tune my vc7 compiled applications to perform at the same or (preferably) better speed of the same vc6 application. Both versions of my code are compiled with optimization, but the vc7 is quite slow in comparison to the vc6 one. My timing test was rougly 71 seconds for vc6 and 103 seconds for vc7. The total...
6
1883
by: abbylee26 | last post by:
Im comparing values in a field while doing a loop if sAct<>myData(5,i) then At the end of the loop I make the value of sAct equal the current myData This will work when comparing other fields withing my recordset (so I know the statement works) but it will not work for the field I want to compare. The only difference with this field is...
12
25973
by: barcaroller | last post by:
Is it legal to compare the contents of two multi-field variables (of the same struct) using "==" and "!="? struct { int a; int b; } x,y; ...
1
4246
by: blazted | last post by:
I am trying to find our how I would compare two matrix's. I have two matrix and I want to find out if they are equal, less or greater than. I created a double loop to loop through and compare an individual element. for(int row = 0; row < Number; row++) { for (int col = 0; col < Number; col++) {
27
3841
by: Thomas Kowalski | last post by:
Hi everyone, To determine equality of two doubles a and b the following is often done: bool isEqual ( double a, double b ) { return ( fabs (a-b) < THRESHOLD ); } But this a approach usually fails if comparing doubles of different magnitude since it's hard or not possible to find a suitable threshold
18
4093
by: Carramba | last post by:
Hi! is there a better/faster way to compare mantissas of to real number then in following code? #include <stdio.h> #include <stdlib.h> int main(void) { float a,b; int test;
5
4507
by: saneman | last post by:
I have a function: int F(double a) { if (a = =1.0) { return 22; } return 44; }
0
7609
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
8118
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...
0
6278
agi2029
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...
1
5504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3651
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
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
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
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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.