Calculating number e c #

I am trying to calculate the number e so that

e = 1 + (1/1! + 1/2! + 1/3! + ..)

      

The user will select the number of samples in this form. the form

 int trialNumber = Convert.ToInt32(Math.Round(trialNumberForm.Value, 0));
        int factorial = trialNumber;
        float factResult = 0;

        for (int i = 1; i < trialNumber; i++)
        {

            for (int b = 1; b < i; b++) //calculates x! here.
            {
                factorial = factorial * b;


            }
           factResult = factResult + (1 / factorial);
        }
        factResult++;
        MessageBox.Show(factResult.ToString());

      

It calculates the result 1 that you have ever chosen! I tried to change the type of the variable to float from double, but that didn't fix it. How to act on the numbers according to the formula I wrote above?

+3


source to share


2 answers


You don't need the factorial (with its integer divisions and integer overflow problems) as

  1/(n+1)! == (1/n!)/(n+1)

      

You can implement computation e

as simple as



  double factResult = 1; // turn double into float if you want
  double item = 1;       // turn double into float if you want

  for (int i = 1; i < trialNumber; ++i)
    factResult += (item /= i);

  ...

  MessageBox.Show(factResult.ToString());

      

results:

   trial number | e
   -------------------------------
              1 | 1
              2 | 2
              3 | 2.5
              4 | 2.666666... 
              5 | 2.708333...
             10 | 2.71828152557319
             15 | 2.71828182845823 
             20 | 2.71828182845905

      

+7


source


As @kabdulla and @ScottChamberlain said, you are doing integer division where you need float division:

for (int b = 1; b < i; b++) //calculates x! here.
{
    factorial = factorial * b;
}
factResult = factResult + (1 / factorial);

      

Should be



for (int b = 2; b < i; b++) //calculates x! here.
{
    factorial = factorial * b;
}
factResult = factResult + (1.0 / factorial);

      

Plus I started the loop for

in b = 2

because multiplication by 1 is useless.

+1


source







All Articles