public BigRational(double value) { var whole = Math.Truncate(value); var wholeRat = new UnsafeBigRational((BigInteger)whole, 1); var frac = value - whole; var scale = Math.Pow(10, frac.ToString().Length - 1); // a power of 10 that moves the fractional part into a whole number var b = new UnsafeBigRational((long)(frac * scale), // multiply frac by scale to get the fractional part as a whole number (long)scale) // then divide the scale back out to turn it back into a fraction... but this time, we're in a rational, so we don't lose info + wholeRat; // Finally, add the whole portion back var gcd = BigInteger.GreatestCommonDivisor(b.Numerator, b.Denominator); // then reduce the resultant fraction this.Numerator = b.Numerator / gcd; this.Denominator = b.Denominator / gcd; }
public static BigRational Sum(this IEnumerable <BigRational> rat) { UnsafeBigRational temp = new UnsafeBigRational(); void Add(BigRational other) { temp.Numerator = (temp.Numerator * other.Denominator) + (other.Numerator * temp.Denominator); temp.Denominator *= other.Denominator; } foreach (var v in rat) { Add(v); } return(temp.Normalize()); }