gpt4 book ai didi

c++ - Raku 中 C++ 和 NativeCall 之间的输出不同

转载 作者:行者123 更新时间:2023-12-01 23:10:35 26 4
gpt4 key购买 nike

我正在尝试为 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 调用相同的代码,所以我修改了代码

测试.cpp

extern "C" double normalCDF( double x )
{
return 0.5 * ( 1.0 + erf( M_SQRT1_2 * x ) );

}

创建了动态共享.so库并将nativecall代码编写为:

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

尽管按照建议使用数据容器,但为什么相同算法的输出不同。

系统信息:

  • Ubuntu 18.04 64 位,带 gcc 6.3.0
  • Rakudo 为 2019.07.1 版本。

最佳答案

您需要以更高的精度打印 float 。以下将为您提供最大精度:

#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 中的前两行,尽管第 2 行才是重要的。

关于c++ - Raku 中 C++ 和 NativeCall 之间的输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58580943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com