Task: Given a numerical series and some number e> 0. Find the sum of those sequence members of the series whose modulus is greater than or equal to the given e.

Given a sequence of the form An = n! / (2n)!

My code is:

class Program { public static double fact(double f) { double fa = 1; for (int i = 1; i <= f; i++) { fa *= i; } return fa; } public static void Main(string[] args) { Console.Write("Enter E = "); double e = System.Convert.ToDouble(Console.ReadLine()); double j = 1; double n = fact(j) / fact(2*j); double sum = 0; while(Math.Abs(n) >= e) { Console.WriteLine(n); sum += n; j++; n = fact(j) / fact(2*j); } Console.WriteLine("SUM= {0}", sum); Console.ReadKey(); } } 

There is a problem when counting, when we start to consider an element in the order of 5 or more.

For example:

A5 = fact (5) / fact (5 * 2); // C # brings us 3,30687830687831E-05

We consider this value manually. We get => fact (5) = 120; fact (10) = 3628800;

120/3628800 = 0.00003306878

Question: Why does C # not calculate this exactly? Because of this, the code ignores these values ​​and, by condition, they do not pass into the sum.

  • 3,30687830687831E-05 equivalent to 3,30687830687831 * 10^-5 or 0,0000330687830687831 - tym32167
  • ru.wikipedia.org/wiki/… - Alex Sherzhukov

1 answer 1

To begin with, your function can be rewritten:

 public static int fact(int f) { int fa = 1; for (int i = f + 1; i <= f*2; i++) { fa *= i; } return fa; } 

Thus, you will only calculate the denominator, which is already abbreviated with the numerator.
This will work faster than separately calculate the numerator and denominator.
Now to calculate the member of your sequence:
double n = 1.0 / fact(i);

* Returns an int because factorial is always integer.


Now, what it displays is 3,30687830687831E-05 instead of 0.00003306878 , then this is the default output for double , which outputs with high precision to change the output (if it confuses you) try changing the number of digits after the comma:
Console.WriteLine("{0:0.000000000}", n);
This output will give 9 digits.
* All calculations are correct.

 public static void Main(string[] args) { double e = 0.00000001; double sum = 0.0; for(int i = 0;;i++){ double n = 1.0 / fact(i); if(n >= e){ sum += n; } else { break; } } Console.WriteLine(sum); } 

Everything works correctly.
When E = 0.00000001 , 8 members are suitable.
If E = 0.000000001 , 11 members are suitable.
Etc.

And it makes no sense from the module, since your number is always positive.