
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Determining Approximate Equality Between a Fraction and Floating-Point Value
|
3
1.1 Determining Approximate Equality Between a
Fraction and Floating-Point Value
Problem
You need to compare a fraction with a value of type double or float to determine
whether they are within a close approximation to each other. Take, for example, the
result of comparing the expression 1/6 and the value 0.16666667. These seem to be
equivalent, except that 0.16666667 is precise to only eight places to the right of the
decimal point, and 1/6 is precise to the maximum number of digits to the right of the
decimal point that the data type will hold.
Solution
To compare the approximate equality between a fraction and a floating-point value,
verify that the difference between the two values is within an acceptable tolerance:
using System;
// Override that uses the System.Double.Epsilon value
public static bool IsApproximatelyEqualTo(double numerator,
double denominator,
double dblValue)
{
return IsApproximatelyEqualTo(numerator,
denominator, dblValue, double.Epsilon);
}
// Override that allows for specification of an epsilon value
// other than System.Double.Epsilon
public static bool IsApproximatelyEqualTo(double numerator,
double denominator,
double dblValue,
double epsilon)
{
double difference = (numerator/denominator) ...