28 DCHECK_LT(
x, std::numeric_limits<double>::infinity());
29 DCHECK_GT(
x, -std::numeric_limits<double>::infinity());
33 long double abs_x = std::abs(
x);
34 long double y = abs_x;
35 int64_t previous_numerator = 0;
36 int64_t previous_denominator = 1;
37 int64_t numerator = 1;
38 int64_t denominator = 0;
40 const int64_t term =
static_cast<int64_t
>(std::floor(
y));
41 const int64_t new_numerator = term * numerator + previous_numerator;
42 const int64_t new_denominator = term * denominator + previous_denominator;
45 if (new_numerator < 0 || new_denominator < 0)
break;
46 previous_numerator = numerator;
47 previous_denominator = denominator;
48 numerator = new_numerator;
49 denominator = new_denominator;
50 long double numerator_approximation = abs_x * denominator;
51 if (std::abs(numerator_approximation - numerator) <=
52 precision * numerator_approximation) {
57 return Fraction((
x < 0) ? -numerator : numerator, denominator);