我尝试将代码从java源代码直接移植到pascal,但是它引发了一个运行时错误。
怎样才能得到适当的高斯曲线?功能内建的帕斯卡呢?
原始源代码:
synchronized public double nextGaussian() {
// See Knuth, ACP, Section 3.4.1 Algorithm C.
if (haveNextNextGaussian) {
haveNextNextGaussian = false;
return nextNextGaussian;
} else {
double v1, v2, s;
do {
v1 = 2 * nextDouble() - 1; // between -1 and 1
v2 = 2 * nextDouble() - 1; // between -1 and 1
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
nextNextGaussian = v2 * multiplier;
haveNextNextGaussian = true;
return v1 * multiplier;
}
}第一次尝试pascal端口(抛出运行时错误):
function log (n : double) : double;
begin
result := ln(n) / ln(10);
end;
var hgauss : boolean;
var ngauss : double;
function gauss() : double;
var x1, x2, w : double;
begin
if hgauss then
begin
result := ngauss;
hgauss := false;
end else
begin
repeat
x1 := 2.0 * rand() - 1.0;
x2 := 2.0 * rand() - 1.0;
w := x1 * x1 + x2 * x2;
until w >= 1.0;
w := sqrt( (-2.0 * log( w ) ) / w );
result := x1 * w;
ngauss := x2 * w;
hgauss := true;
end;
end; 这里的浮点操作无效:
w := sqrt((-2.0 * log( w ) ) / w);第二次尝试转换(运行,但我不确定数学是否正确):
function log (n : double) : double;
begin
result := ln(n) / ln(10);
end;
var hgauss : boolean;
var ngauss : double;
function gauss() : double;
var x1, x2, w, num : double;
begin
if hgauss then
begin
result := ngauss;
hgauss := false;
end else
begin
repeat
x1 := 2.0 * rand() - 1.0;
x2 := 2.0 * rand() - 1.0;
w := x1 * x1 + x2 * x2;
until w >= 1.0;
num := -2.0 * log( w ) / w;
w := sqrt(abs(num));
if num < 0 then w := -w;
result := x1 * w;
ngauss := x2 * w;
hgauss := true;
end;
end;发布于 2016-07-14 07:56:42
rand()在[0,1)范围内( 0 <= rand() < 1 )
所以2.0 * rand() - 1.0在[-1,1)范围内
所以x1和x2在[-1,1)范围内
所以w := x1 * x1 + x2 * x2在[0,2)范围内
在sqrt( -2.0 * ln( w ) / w )中,w是阳性的
所以自然对数: ln(w)应该是负的。
所以w应该在(0,1)范围内
所以循环不应该退出until (w > 0.0)and (w < 1.0);
工作示例代码(使用SCAR Divi 3.41.00):
program New;
var hgauss : boolean;
var ngauss : double;
function gauss() : double;
var x1, x2, w : double;
begin
if hgauss then
begin
result := ngauss;
hgauss := false;
end else
begin
repeat
x1 := 2.0 * rand() - 1.0;
x2 := 2.0 * rand() - 1.0;
w := x1 * x1 + x2 * x2;
until (w > 0.0)and (w < 1.0);
w := sqrt( -2.0 * ln( w ) / w );
result := x1 * w;
ngauss := x2 * w;
hgauss := true;
end;
end;
begin
writeln( gauss() );
writeln( gauss() );
end.发布于 2016-07-14 06:48:35
您从Java到Pascal的端口在一个重要部分是错误的
do {...} while (s >= 1 || s == 0);
应该翻译成
repeat {...} until ((s<1) and (s<>0));
所以你有错误的终止条件。如果是0 < s < 1,Java会终止循环,但是如果是w >= 1,循环就会结束。
如果w > 1有-2*ln(w) < 0,浮点异常来自负数的平方根!
对于大多数Pascal版本,您对标准函数的命名是不寻常的,IMO应该是这样的。
repeat
x1 := 2.0 * random - 1.0;
x2 := 2.0 * random - 1.0;
w := x1 * x1 + x2 * x2;
until (w<1.0) and (w>0.0);
w := sqrt(-2.0*ln(w)/w);
result := x1 * w;
ngauss := x2 * w;请注意,您确实必须使用ln,而不是自制的-10对数log。使用的方法是Marsaglia极地法
https://stackoverflow.com/questions/38364880
复制相似问题