home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13580 < prev    next >
Encoding:
Text File  |  1992-09-13  |  1.8 KB  |  60 lines

  1. 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
  2. From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Need Help on trivial issue
  5. Message-ID: <9225803.11121@mulga.cs.mu.OZ.AU>
  6. Date: 13 Sep 92 17:33:08 GMT
  7. References: <14497@goanna.cs.rmit.oz.au>
  8. Sender: news@cs.mu.OZ.AU
  9. Organization: Computer Science, University of Melbourne, Australia
  10. Lines: 48
  11.  
  12. gtj@goanna.cs.rmit.oz.au (Glenn T Jayaputera) writes:
  13.  
  14. >Hi, I need help on the following program.  The problem I have is if I
  15. >input the value > 1.1 the string "Yahooo....." is only printed once.
  16. >I dont Understand why n==of only for a value of 0.5 not 1.0, 1.5, 2.0, etc.
  17. >
  18. >Can somebody please pointed out which part I am missing.
  19. >
  20. >#include <iostream.h>
  21. >
  22. >main()  {
  23. >  double x;
  24. >  double n=0.1, of=0.5;
  25. >
  26. >  cout << "Input x : "; cin >> x;
  27. >
  28. >  while (n<x)  {
  29. >    n += 0.1;
  30. >    if (n==of)  {
  31. >      cout << "Yahooooo...\n";
  32. >      of +=0.5;
  33. >    }
  34. >  }
  35. >}
  36.  
  37. The problem is caused by rounding errors. n will have a value like
  38.     0.9999999999999999999
  39. and the test "if (n == 1.0)" will fail.
  40.  
  41. Because of this problem, you should almost never use equality tests between
  42. floating point numbers, and a good compiler would warn you when you do.
  43. Instead you should rephrase the test as
  44.     const double tolerance = 1.0E-6;
  45.     ...
  46.     if (fabs(n-of) < tolerance) {        // absolute difference less
  47.                         // than tolerance
  48. or
  49.     if (fabs(n-of) / fabs(of) < tolerance) {
  50.                         // relative difference less
  51.                         // than tolerance
  52.  
  53. Read any good book on numerical computation.
  54.  
  55. -- 
  56. Fergus Henderson             fjh@munta.cs.mu.OZ.AU      
  57. This .signature virus is a self-referential statement that is true - but 
  58. you will only be able to consistently believe it if you copy it to your own
  59. .signature file!
  60.