我正在尝试为cumulative distribution function中的here编写一个函数。
这是我的cpp
代码:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
int main() {
cout << normalCDF(4.8) << endl;
cout << normalCDF(5.4) << endl;
cout << normalCDF(5.6) << endl;
cout << normalCDF(5.8) << endl;
cout << normalCDF(5.1) << endl;
cout << normalCDF(-37.5) << endl;
cout << normalCDF(-36.0) << endl;
cout << normalCDF(-37.6) << endl;
cout << normalCDF(-37.5) << endl;
return 0;
}
这是在Linux中使用gcc 6.3.0编译时的输出
0.999999
1
1
1
1
0
0
0
0
我想使用NativeCall从raku调用相同的代码,所以我修改了代码
test.cpp
extern "C" double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
创建了动态共享.so
库,并将本地调用代码编写为:
use NativeCall;
sub normalCDF(num64) returns num64 is native('libtest.so') { * };
say normalCDF((4.8).Num);
say normalCDF((5.4).Num);
say normalCDF((5.6).Num);
say normalCDF((5.8).Num);
say normalCDF((5.1).Num);
say normalCDF((-37.5).Num);
say normalCDF((-36.0).Num);
say normalCDF((-37.6).Num);
say normalCDF((-37.5).Num);
输出为:
0.999999206671848
0.9999999666795515
0.9999999892824097
0.9999999966842541
0.9999998301732593
0
0
0
0
尽管推荐使用数据容器,但为什么相同算法的输出却不同?
系统信息:
答案 0 :(得分:8)
您需要以更高的精度打印浮点数。以下将为您提供最大的精度:
#include <limits>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );
}
int main() {
typedef std::numeric_limits< double > dmax;
cout.precision(dmax::max_digits10);
cout << normalCDF(4.8) << endl;
cout << normalCDF(5.4) << endl;
cout << normalCDF(5.6) << endl;
cout << normalCDF(5.8) << endl;
cout << normalCDF(5.1) << endl;
cout << normalCDF(-37.5) << endl;
cout << normalCDF(-36.0) << endl;
cout << normalCDF(-37.6) << endl;
cout << normalCDF(-37.5) << endl;
return 0;
}
请注意#include <limits>
和main
中的前两行,尽管第二行很重要。