Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that safely compares floating-point numbers (double) with precision
- * eps = 0.000001. 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.
- * Therefore, we assume two numbers are equal if they are more closely
- * to each other than a fixed constant eps. */
- namespace _13.ComparingFloats
- {
- using System;
- public class SafelyComparingFloats
- {
- private const double EPS = 0.000001d;
- public static void Main(string[] args)
- {
- checked
- {
- Console.Write("Enter the First real number: ");
- double numA = double.Parse(Console.ReadLine());
- Console.Write("Enter the Second real number: ");
- double numB = double.Parse(Console.ReadLine());
- if (!double.Equals(numA, numB))
- {
- if (numA < 0 && numB < 0)
- {
- numA = Math.Abs(numA);
- numB = Math.Abs(numB);
- }
- double difference = Math.Abs(numA - numB);
- if (difference < EPS)
- {
- Console.WriteLine("These two Float-Point numbers IS EQUALS !");
- Console.WriteLine("The Difference is too small: {0:F8} !", difference);
- }
- else
- {
- Console.WriteLine("These two Float-Point numbers is NOT EQUALS !");
- Console.WriteLine("The Difference is: {0} !", difference);
- }
- }
- else
- {
- Console.WriteLine("These two Float-Point numbers IS EQUALS !");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement