Calculate sum of 1+(1/2!)+…+(1/n!) n number in C language

后端 未结 4 1360
情歌与酒
情歌与酒 2021-01-24 08:44

Like the title say, how I calculate the sum of n number of the form: 1+(1/2!)+⋯(1/n!)? I already got the code for the harmonic series:

#include 

         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 09:13

    You got a slightly more accurate answer for the harmonic summing 1./i + 1./(i-1) ... 1./1. Suggest you stay with that order.

    [edit] Rewrite: Thanks to @pablo197 for pointing out the error of my ways.

    To calculate harmonic and 1+(1/2!)+…+(1/n!), continue summing the least significant terms together first as that helps to minimize precision loss. Starting with the least significant term 1/n as sum, sum of that and the n-1 term is : sum = (1 + sum)/(n-1) and so on. (See below)

    double x = 0.0;
    double one_over_factorial_series = 0.0;
    for (i = v; i >= 1; i--) {
      x += 1.0/i;
      one_over_factorial_series = (one_over_factorial_series + 1)/i;
    }
    printf("harmonic:%le\n", x); 
    // 2.828968e+00
    printf("one_over_factorial:%.10le\n", one_over_factorial_series); 
    // 1.7182815256e+00
    

    Add 1.0 or 1/0! to one_over_factorial_series, the result about e = 2.7182818284...

    [Edit] Detail showing how direct n! calculation is avoided.

    1 + (1/2!) + … + (1/n!) =  
    1/n!  +  1/((n-1)!)   +  1/((n-2)!)  +  1/((n-3)!)  + ... + 1 =  
    (1/n + 1)/((n-1)!)    +  1/((n-2)!)  +  1/((n-3)!)  + ... + 1 =  
    ((1/n + 1)/(n-1) + 1)/((n-2)!)       +  1/((n-3)!)  + ... + 1 =  
    ...
    ((((1/n + 1)/(n-1) + 1)/(n-2) + 1)/(n-3) + 1)/(n-4) + ... =  
    

提交回复
热议问题