Advertisement
VKNikov

Comparing floating-point numbers

Mar 15th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 KB | None | 0 0
  1. //Comparing Floats
  2. //Write a program that safely compares floating-point numbers (double) with precision eps = 0.000001.
  3. //Note that we cannot directly compare two floating-point numbers a and b by a==b because of the nature of the floating-point arithmetic.
  4. //Therefore, we assume two numbers are equal if they are more closely to each other than a fixed constant eps. Examples:
  5.  
  6. using System;
  7.  
  8. class ComparingFloats
  9. {
  10.     static void Main()
  11.     {
  12.         Console.WriteLine("This program compares two floating point numbers up to epsilon 0.000001.\nIf the difference between the two numbers is greater than epsilon,\nthe program will consider the numbers to be different.");
  13.         Console.WriteLine("\nPlease type in the first number: ");
  14.         double firstnumber = double.Parse(Console.ReadLine());
  15.         Console.WriteLine("Please type in the second number:");
  16.         double secondnumber = double.Parse(Console.ReadLine());
  17.         double diff = Math.Abs(firstnumber - secondnumber);
  18.         double eps = 0.000001;
  19.         bool check = diff < eps;
  20.         Console.WriteLine("Is number {0} equal to number {1}? True or False?", firstnumber, secondnumber);
  21.         Console.WriteLine(check);
  22.         Console.WriteLine("\nPress any key to exit."); //The last two lines are added so the program will not automatically close if it is run outside the IDE, as a standalone application.
  23.         Console.ReadKey();
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement