在C中计算系列

时间:2018-11-20 21:06:44

标签: c series

此图像是我应该做的任务:

i should calculate this serie

无论我在-1和1之间输入什么,输出始终为1.0000或2.0000。我该如何解决这个问题?下面我附上我的代码。

#include <stdio.h>
#include <math.h>


int main() {

    int i;
    float x;
    float sum=0;


    printf ("enter an x\n");
    scanf ("%f",&x);

    if ((x>-1)&&(x<1))
    {
         for (i=0;i<101;i++)
         sum= sum + (pow(x,i));
    }    

    printf ("result=%f",sum);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

if ((x>-1)&&(x<1))

在这种情况下,仅当x为零时,您的代码才能工作,因此请尝试删除if语句,并提及您希望给定特定输入的输出,回答它会更有帮助。

尝试以下代码:

#include <stdio.h> 
#include <math.h> 
int main() { 
    int i; float x; 
    float sum=0; 

    printf ("enter an x\n"); 
    scanf ("%f",&x); 
    for (i=0 ;i<101; i++) 
        sum+= (pow(x,i)); 

    printf ("result=%f",sum); 
    return 0;
}

答案 1 :(得分:0)

即使使用double之类的类型,您也没有足够的数值精度来求和所有功率 达100。

执行以下代码段时,您会注意到,虽然评估了正确的(从数字上来说)结果,但循环在第100次迭代之前停止,通常在16:

#include <stdio.h>
#include <math.h>
#include <float.h>

// Analytically calculates the limit for n -> inf of the series of powers
double sum_of_powers_limit(double x)
{
    return 1.0 / (1.0 - x);
}

int main(void)
{
    double x = 0.1;
    const int N = 100;
    double sum = 1.0;

    for (int i = 1; i <= N; ++i)
    {
        double old_sum = sum;
        sum = sum + pow(x,i);

        if (old_sum == sum)
        {
            fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
            break;
        }
    }

    printf("  result = %.*e\n", DBL_DECIMAL_DIG, sum);
    printf("expected = %.*e\n", DBL_DECIMAL_DIG, sum_of_powers_limit(x));

    return 0;
}

还要注意,评估这种多项式的更有效方法是Horner's method

// Evaluates the sum s(x) = 1 + x + x^2 + ... + x^n using Horner's method
// It stops when it cannot update the value anymore
double sum_of_powers(double x, int n)
{
    double result = 1.0;
    for (int i = 0; i < n; ++i)
    {
        double old_result = result;
        result = 1.0 + x * result;

        if (old_result == result)
        {
            fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
            break;
        }
    }
    return result;
}