Knowledge point:
1. Double. Epsilon field and single. Epsilon Field
2. Comparison of float and double approximation values
Problem:
You need to compare a score with a double or float value to determine whether they are very close to each other. For example, let's look at the comparison result of expression 1/6 and value 0.16666667. It seems that the two are equal, but 0.16666667 is accurate to the eight digits to the right of the decimal point, and 1/6 is precise to the maximum digits allowed by the data type to the right of the decimal point.
Solution:
To compare the Approximate Equality between a score and a floating point value, you need to check whether the difference between the two values is within an acceptable range:
1 using system; 2 using system. collections. generic; 3 using system. LINQ; 4 using system. text; 5 using system. threading. tasks; 6 7 namespace _ 03 determine approximate equality between scores and floating point values 8 {9 class program10 {11 static void main (string [] ARGs) 12 {13 console. writeline ("the first number of input molecules:"); 14 var Numerator = console. readline (); 15 console. writeline ("denominator of the first input number:"); 16 var Denominator = console. readline (); 17 console. writeline ("enter a floating point comparison value:"); 18 var dblvalue = console. readline (); 19 console. writeline ("Please input precision:"); 20 var Epsilon = console. readline (); 21 bool isgoodapproximate = isapproximatelyequalto (convert. todouble (numerator), convert. todouble (denominator), convert. todouble (dblvalue), convert. todouble (epsilon); 22 if (isgoodapproximate) 23 {24 console. writeline ("Good approximate"); 25} 26 else27 {28 console. writeline ("Bad approximate"); 29} 30 console. readkey (); 31} 32 33 // use system. double. epsilon value 34 public static bool isapproximatelyequalto (double numerator, double denominator, double dblvalue) 35 {36 return isapproximatelyequalto (numerator, denominator, dblvalue, double. epsilon); 37} 38 39 Private Static bool isapproximatelyequalto (double numerator, double denominator, double dblvalue, double epsilon) 40 {41 Double Difference = (numerator/denominator)-dblvalue; 42 if (math. ABS (difference) <epsilon) 43 {44 // This is a good approximation (approximate enough) 45 return true; 46} 47 else48 {49 // This is a bad approximation (not approximate enough) 50 return false; 51} 52} 53 54} 55}View code
Result:
Bool isgoodapproximate = isapproximatelyequalto (142857,. 0000001 );
// Approximate = false
Bool isgoodapproximate = isapproximatelyequalto (1428571,. 0000001 );
// Approximate = true
1.1 determine the Approximate Equality between the score and the floating point value.