无论是C ++还是C,相同的数字代码都会返回不同的输出

时间:2017-01-07 15:59:12

标签: c++ c numerical derivative calculus

我得到了一个示例C ++数字代码,以三种不同的方式计算衍生物。我必须将其转换为C.我认为由于原来使用cmath它不会给我任何问题,但我错了。这是原始代码:

#include <iostream>
#include<string>
#include <cmath>
#include <fstream>
using namespace std;


double metoda_pochodna_1(int x, double h)
{
    return (sin(x+h) - sin(x)) / h;
}   
double metoda_pochodna_2(int x, double h)
{
    return (sin(x+(0.5*h)) - sin(x-(0.5*h))) / h;
}
double metoda_pochodna_3(int x, double h)
{
    return ((sin(x-2*h) - 8*sin(x-h) + 8*sin(x+h) - sin(x+2*h)) / (12*h));
}


int main()
{
    double h, w1, w2, w3, kos = cos(1.0);
    int x=1;
    ofstream wyniki;
    wyniki.open("wyniki.dat");

    for (h = pow(10.0, -15.0); h < 1; h *= 1.01) 
    {
        w1 = log10(abs(metoda_pochodna_1(x,h) - kos));
        w2 = log10(abs(metoda_pochodna_2(x,h) - kos));
        w3 = log10(abs(metoda_pochodna_3(x,h) - kos));
        wyniki << log10(h)<<"  "<< w1 <<"  "<< w2 <<"  "<< w3 << "\n";
        cout << log10(h)<<"  "<< w1 <<"  "<< w2 <<"  "<< w3 << "\n";
    }

    wyniki.close();
    cout << endl;
    /*system("pause");*/ //uruchamiane z windowsa
    return 0;
}

这是我的C版;我只是改变了文件处理。注意:我在故障排除期间更改为long double,但结果输出与使用常规double的版本完全相同。

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



long double metoda_pochodna_1(int x,long  double h)
{
    return (sin(x+h) - sin(x)) / h;
}   
long double metoda_pochodna_2(int x,long  double h)
{
    return (sin(x+(0.5*h)) - sin(x-(0.5*h))) / h;
}
long double metoda_pochodna_3(int x, long double h)
{
    return ((sin(x-2*h) - 8*sin(x-h) + 8*sin(x+h) - sin(x+2*h)) / (12*h));
}


int main()
{
    long double h, w1, w2, w3, kos = cos(1.0);
    int x=1;
    FILE * file;
    file = fopen("wyniki.dat","w+");


    for (h = pow(10.0, -15.0); h < 1; h *= 1.01) 
    {
        w1 = log10(abs(metoda_pochodna_1(x,h) - kos));
        w2 = log10(abs(metoda_pochodna_2(x,h) - kos));
        w3 = log10(abs(metoda_pochodna_3(x,h) - kos));
        fprintf(file,"%f %Lf %Lf %Lf\n",log10(h), w1,w2,w3);
        printf("%f %Lf %Lf %Lf\n",log10(h), w1,w2,w3);
        //wyniki << log10(h)<<"  "<< w1 <<"  "<< w2 <<"  "<< w3 << "\n";
        //cout << log10(h)<<"  "<< w1 <<"  "<< w2 <<"  "<< w3 << "\n";
    }

    fclose(file);
    printf("\n");
    return 0;
}

这是C ++代码的输出,我假设是正确的:

-15  -1.82947  -1.82947  -1.28553

-14.9957  -2.03091  -2.03091  -1.33768

14.9914  -2.41214  -2.41214  -1.39632

-14.987  -2.81915  -2.81915  -1.46341
     

[...]

这是C版本的输出,显然有所不同(前排的额外精度来自long double,但其他三列都是-inf,无论是double或使用long double

-15.000000 -inf -inf -inf

-14.995679 -inf -inf -inf

-14.991357 -inf -inf -inf

-14.987036 -inf -inf -inf
     

[...]

我的转换代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

您正在使用abs这是一个整数函数。 C浮点函数为fabs。 将您的三行更改为

w1 = log10(fabs(metoda_pochodna_1(x,h) - kos));
w2 = log10(fabs(metoda_pochodna_2(x,h) - kos));
w3 = log10(fabs(metoda_pochodna_3(x,h) - kos));

程序输出更明智的值。