Advertisement
viraldim

ComparingFloats

Mar 9th, 2014
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. /*Problem 3: Write a program that safely compares floating-point numbers with precision
  2. eps = 0.000001. Note that we cannot directly compare two floating-point numbers a and b by a==b
  3. because of the nature of the floating-point arithmetic. Therefore, we assume two numbers
  4. are equal if they are more closely to each other than a fixed constant eps. */
  5.  
  6. using System;
  7.  
  8. class ComparingFloats
  9. {
  10. static void Main()
  11. {
  12. float eps = 0.000001f;
  13. bool result = true;
  14.  
  15. Console.WriteLine("Enter a number to compare");
  16. //reading the numbers from the console and taking their absolute value
  17. double firstNumber = Math.Abs(double.Parse(Console.ReadLine()));
  18. Console.WriteLine("Enter a number to compare");
  19. double secondNumber = Math.Abs(double.Parse(Console.ReadLine()));
  20.  
  21. if (firstNumber>secondNumber)
  22. {
  23. result = firstNumber - secondNumber < eps;
  24. }
  25. else
  26. {
  27. result = secondNumber - firstNumber < eps;
  28. }
  29.  
  30. Console.WriteLine(result);
  31. }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement