OLD | NEW |
(Empty) | |
| 1 static const int kBufferSize = 50; |
| 2 |
| 3 static double ComposeDouble(char* buffer, int sign, int length, int point) { |
| 4 int k = point - length; |
| 5 // Integrate exponent into buffer. |
| 6 buffer[length] = 'e'; |
| 7 snprintf(&buffer[length+1], kBufferSize - length - 1, "%d", k); |
| 8 double result; |
| 9 sscanf(buffer, "%lf", &result); // NOLINT |
| 10 if (sign) { |
| 11 result *= -1; |
| 12 } |
| 13 return result; |
| 14 } |
| 15 |
| 16 |
| 17 static bool IsCorrect(double v, char* buffer, int sign, int length, int point) { |
| 18 return v == ComposeDouble(buffer, sign, length, point); |
| 19 } |
| 20 |
| 21 |
| 22 // The precision of long doubles is not enough to ensure the correct rounding. |
| 23 static bool IsRounded(double v, char* buffer, int sign, int length, int point) { |
| 24 // We don't test when v is 0. |
| 25 if (v == 0) return true; |
| 26 |
| 27 // Simplify things by working with positive numbers. |
| 28 if (v < 0) v = -v; |
| 29 char correct_buffer[100]; |
| 30 snprintf(correct_buffer, sizeof(correct_buffer), "%.90e", v); |
| 31 // Get rid of the '.' |
| 32 correct_buffer[1] = correct_buffer[0]; |
| 33 char* correct_str = &correct_buffer[1]; |
| 34 |
| 35 int i = 0; |
| 36 while (true) { |
| 37 if (correct_str[i] == '\0' || correct_str[i] == 'e') { |
| 38 // We should never need all digits. |
| 39 return false; |
| 40 } |
| 41 |
| 42 if (buffer[i] == '\0' || buffer[i] == 'e') { |
| 43 // Verify that the remaining correct digits are small enough. |
| 44 if (correct_str[i] < '5') return true; |
| 45 return false; // For simplicity we assume that '5' is rounded up. |
| 46 } |
| 47 |
| 48 if (buffer[i] != correct_str[i]) { |
| 49 if (buffer[i] < correct_str[i]) return false; |
| 50 if (buffer[i] - correct_str[i] != 1) return false; |
| 51 if (correct_str[i+1] < '5') return false; |
| 52 return true; |
| 53 } |
| 54 |
| 55 // Both characters are equal |
| 56 i++; |
| 57 } |
| 58 } |
| 59 |
| 60 |
| 61 static bool IsShortest(double v, |
| 62 char* buffer, |
| 63 int sign, |
| 64 int length, |
| 65 int point) { |
| 66 // Now test if a shorter version would still yield the same result. |
| 67 // Not an exhaustive test, but better than nothing. |
| 68 |
| 69 if (length == 1) return true; |
| 70 |
| 71 char last_digit = buffer[length - 1]; |
| 72 |
| 73 if (buffer[length - 1] == '0') return false; |
| 74 |
| 75 if (v == ComposeDouble(buffer, sign, length - 1, point)) { |
| 76 return false; |
| 77 } |
| 78 |
| 79 bool result = true; |
| 80 if (buffer[length-2] != '9') { |
| 81 buffer[length - 2]++; |
| 82 double changed_value = ComposeDouble(buffer, sign, length-1, point); |
| 83 if (v == changed_value) { |
| 84 printf("ROUNDED FAILED DEBUG: %s\n", buffer); |
| 85 result = false; |
| 86 } |
| 87 buffer[length - 2]--; |
| 88 } |
| 89 buffer[length - 1] = last_digit; |
| 90 return result; |
| 91 } |
OLD | NEW |