fork download
  1. // This is in the public domain
  2. using System;
  3. using System.Numerics;
  4. using static System.Console;
  5.  
  6. public static class Program
  7. {
  8. private static readonly string Rod = new string('-', 64);
  9.  
  10. public static void Main()
  11. {
  12. Test(Square(Math.PI), x => ToRational(x), n => (double)n);
  13. Test(Square((decimal)Math.PI), x => ToRational(x), n => (decimal)n);
  14. }
  15.  
  16. private static double Square(double x) => x * x;
  17.  
  18. private static decimal Square(decimal x) => x * x;
  19.  
  20. private static void Test<T>(T value, Func<T, ValueTuple<BigInteger, BigInteger>> toRational, Func<BigInteger, T> toT)
  21. {
  22. WriteLine(Rod);
  23. WriteLine($"value = {value}");
  24. var rational = toRational(value);
  25. BigInteger num = rational.Item1, den = rational.Item2;
  26. WriteLine($"rational = {num}/{den}");
  27. WriteLine($"rational - value = {(dynamic)toT(num) / toT(den) - value}");
  28. }
  29.  
  30. private static (BigInteger num, BigInteger den) ToRational(double value)
  31. {
  32. var gcd = GCD(value, 1);
  33. return ((BigInteger)(value / gcd), (BigInteger)(1 / gcd));
  34. }
  35.  
  36. private static (BigInteger num, BigInteger den) ToRational(decimal value)
  37. {
  38. var gcd = GCD(value, 1);
  39. return ((BigInteger)(value / gcd), (BigInteger)(1 / gcd));
  40. }
  41.  
  42. private static double GCD(double m, double n)
  43. {
  44. while (n != 0)
  45. {
  46. var rem = m % n;
  47. m = n;
  48. n = rem;
  49. }
  50. return m;
  51. }
  52.  
  53. private static decimal GCD(decimal m, decimal n)
  54. {
  55. while (n != 0)
  56. {
  57. var rem = m % n;
  58. m = n;
  59. n = rem;
  60. }
  61. return m;
  62. }
  63. }
Success #stdin #stdout 0.29s 33852KB
stdin
Standard input is empty
stdout
----------------------------------------------------------------
value = 9.86960440108936
rational = 2778046668940015/281474976710656
rational - value = 0
----------------------------------------------------------------
value = 9.869604401089338270973592244
rational = 2467401100272334567743398061/250000000000000000000000000
rational - value = 0.000000000000000000000000000