简体   繁体   English

这个功能纯吗? (随机计算,确定性结果)

[英]Is this function pure? (Random computation, deterministic result)

A pure function is defined as a function that: 纯函数定义为以下函数:

  1. Returns the same value for the same arguments, and 对于相同的参数返回相同的值,并且
  2. Does not produce any side effects (mutation of non-local variables, I/O operations, etc.) 不产生任何副作用(非局部变量的突变,I / O操作等)

Consider a function that calculates the greatest common divisor of two positive integers by randomly sampling integers between 1 and the lowest of the two numbers, and determining if the sampled integer divides the two given integers. 考虑一个函数,该函数通过随机采样介于1和两个数字中的最小值之间的整数,并确定采样的整数是否除以两个给定的整数,来计算两个正整数的最大公约数。 When all of the integers have been visited, the function returns the highest sampled integer. 当访问完所有整数后,该函数将返回采样率最高的整数。 Assume the random number generator used is uniform. 假设使用的随机数生成器是统一的。

Intuitively, it seems to me that this function is pure , despite its computation being non-deterministic. 凭直觉,在我看来,此函数是函数,尽管其计算是不确定的。 It produces the same value for the same arguments, and does not produce any side effects. 它为相同的参数产生相同的值,并且不会产生任何副作用。 The only possible "side effect" I can think of is there is the possibility of the computation going on forever, given a large enough input. 我能想到的唯一可能的“副作用”是,在输入足够大的情况下,计算可能会永远进行下去。 Am I correct in labeling this function pure ? 我是否正确地将此函数标记为函数?

No, I don't think so. 不,我不这么认为。

As for random number generators, there are two possibilities: 对于随机数生成器,有两种可能性:

  1. It is a Pseudo-RNG. 它是伪RNG。 It means it has an N-bit state, and each time a new random number is generated, the state gets updated. 这意味着它具有N位状态,并且每次生成新的随机数时,该状态都会更新。 So there is a side effect - a change in the RNG state. 因此有一个副作用-RNG状态发生变化。

  2. A True random generator, which draws random bits from entropy source. 真正的随机数生成器,它从熵源中提取随机位。 Again, the pool will be drawn upon and might be exhausted - here is a sign of a non-pure function. 同样,该池将被使用并且可能已用尽-这是一个非纯函数的信号。

A "random number generator" can't be a pure function unless all the information it needs to generate a random-looking number is passed to it up front. 除非“生成随机数生成器”需要生成随机数的所有信息,否则“纯随机数生成器”不能是纯函数。 If the generator uses anything else (such as the system clock or the file system), the generator will not be pure. 如果生成器使用其他任何东西(例如系统时钟或文件系统),则生成器将不是纯粹的。 For example, pure functions include: 例如,纯函数包括:

  • Hash functions. 哈希函数。
  • Functions that take a seed and output a random-looking number and a new seed. 带有种子并输出随机数和新种子的函数。
  • Functions that take an internal state and output a random-looking number and a new internal state. 具有内部状态并输出随机数和新内部状态的函数。

See my section " Designs for PRNGs ". 参见我的“ PRNG设计 ”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM