如何在 Prolog 中生成正态分布的随机数?
How to generate normal distributed random numbers in Prolog?
我是 Prolog 的初学者。我想知道如何在 Prolog 中生成正态分布的随机数。
我所知道的是使用 library(random)
中的 maybe
可以设置概率。但是当涉及到随机分布时呢?
通常,语言为您提供 0 到 1 的均匀分布。有多种算法可以从该均匀分布到另一个分布,但这种情况特别常见,因此有几种方法可以做到这一点。
如果您需要正态分布中的适量随机值,Box-Muller transform 是一个非常简单的算法,它相当于对一些均匀随机值进行一些数学运算:
random_normal(N) :-
random(U1), random(U2),
Z0 is sqrt(-2 * log(U1)) * cos(2*pi*U2),
Z1 is sqrt(-2 * log(U1)) * sin(2*pi*U2),
(N = Z0 ; N = Z1).
该算法消耗两个统一值并产生两个正常值。我提供这两种解决方案。对于某些应用程序,执行此操作的其他方法可能更好。例如,您可以使用 asserta/1
和 retract/1
来缓存第二个值并在不进行计算的情况下使用它,尽管在动态存储中乱搞可能和做其他工作一样糟糕(你有对其进行基准测试)。用法如下:
?- random_normal(Z).
Z = -1.2418135230345024 ;
Z = -1.1135242997982466.
?- random_normal(Z).
Z = 0.6266801862581797 ;
Z = -0.4934840828548163.
?- random_normal(Z).
Z = 0.5525713772053663 ;
Z = -0.7118660644436128.
我对此不是很有信心,但它可能会让你渡过难关。
如果您使用的是 SWI-Prolog 或 SWISH,那么另一种选择是使用嵌入式 R,这为您提供了统计和概率方面的很大灵活性。
http://swish.swi-prolog.org/example/Rserve.swinb
The R project provides statistical computing and data vizualization. SWISH can access R through Rserve.
Integrative statistics with R:
Real is a c-based interface for connecting R to Prolog. See the documentation at doc/html/real.html for more information. There is also a paper [1] and a user's guide in doc/guide.pdf.
Real works on current versions of SWI and YAP. As of version 1.1 there is support for using Real on SWI web-servers.
我是 Prolog 的初学者。我想知道如何在 Prolog 中生成正态分布的随机数。
我所知道的是使用 library(random)
中的 maybe
可以设置概率。但是当涉及到随机分布时呢?
通常,语言为您提供 0 到 1 的均匀分布。有多种算法可以从该均匀分布到另一个分布,但这种情况特别常见,因此有几种方法可以做到这一点。
如果您需要正态分布中的适量随机值,Box-Muller transform 是一个非常简单的算法,它相当于对一些均匀随机值进行一些数学运算:
random_normal(N) :-
random(U1), random(U2),
Z0 is sqrt(-2 * log(U1)) * cos(2*pi*U2),
Z1 is sqrt(-2 * log(U1)) * sin(2*pi*U2),
(N = Z0 ; N = Z1).
该算法消耗两个统一值并产生两个正常值。我提供这两种解决方案。对于某些应用程序,执行此操作的其他方法可能更好。例如,您可以使用 asserta/1
和 retract/1
来缓存第二个值并在不进行计算的情况下使用它,尽管在动态存储中乱搞可能和做其他工作一样糟糕(你有对其进行基准测试)。用法如下:
?- random_normal(Z).
Z = -1.2418135230345024 ;
Z = -1.1135242997982466.
?- random_normal(Z).
Z = 0.6266801862581797 ;
Z = -0.4934840828548163.
?- random_normal(Z).
Z = 0.5525713772053663 ;
Z = -0.7118660644436128.
我对此不是很有信心,但它可能会让你渡过难关。
如果您使用的是 SWI-Prolog 或 SWISH,那么另一种选择是使用嵌入式 R,这为您提供了统计和概率方面的很大灵活性。
http://swish.swi-prolog.org/example/Rserve.swinb
The R project provides statistical computing and data vizualization. SWISH can access R through Rserve.
Integrative statistics with R:
Real is a c-based interface for connecting R to Prolog. See the documentation at doc/html/real.html for more information. There is also a paper [1] and a user's guide in doc/guide.pdf.
Real works on current versions of SWI and YAP. As of version 1.1 there is support for using Real on SWI web-servers.