home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!pmafire!news.dell.com!swrinde!zaphod.mps.ohio-state.edu!rpi!batcomputer!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
- From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
- Newsgroups: comp.lang.c++
- Subject: Re: Need Help on trivial issue
- Message-ID: <9225803.11121@mulga.cs.mu.OZ.AU>
- Date: 13 Sep 92 17:33:08 GMT
- References: <14497@goanna.cs.rmit.oz.au>
- Sender: news@cs.mu.OZ.AU
- Organization: Computer Science, University of Melbourne, Australia
- Lines: 48
-
- gtj@goanna.cs.rmit.oz.au (Glenn T Jayaputera) writes:
-
- >Hi, I need help on the following program. The problem I have is if I
- >input the value > 1.1 the string "Yahooo....." is only printed once.
- >I dont Understand why n==of only for a value of 0.5 not 1.0, 1.5, 2.0, etc.
- >
- >Can somebody please pointed out which part I am missing.
- >
- >#include <iostream.h>
- >
- >main() {
- > double x;
- > double n=0.1, of=0.5;
- >
- > cout << "Input x : "; cin >> x;
- >
- > while (n<x) {
- > n += 0.1;
- > if (n==of) {
- > cout << "Yahooooo...\n";
- > of +=0.5;
- > }
- > }
- >}
-
- The problem is caused by rounding errors. n will have a value like
- 0.9999999999999999999
- and the test "if (n == 1.0)" will fail.
-
- Because of this problem, you should almost never use equality tests between
- floating point numbers, and a good compiler would warn you when you do.
- Instead you should rephrase the test as
- const double tolerance = 1.0E-6;
- ...
- if (fabs(n-of) < tolerance) { // absolute difference less
- // than tolerance
- or
- if (fabs(n-of) / fabs(of) < tolerance) {
- // relative difference less
- // than tolerance
-
- Read any good book on numerical computation.
-
- --
- Fergus Henderson fjh@munta.cs.mu.OZ.AU
- This .signature virus is a self-referential statement that is true - but
- you will only be able to consistently believe it if you copy it to your own
- .signature file!
-