是一个调用Math.random()纯函数的函数吗? [英] Is a function that calls Math.random() pure?

查看:223
本文介绍了是一个调用Math.random()纯函数的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数test(min,max){
return Math.random ()*(max - min)+ min;
}

我的理解是纯函数遵循以下条件: b
$ b


  1. 它返回一个从参数计算出来的值

  2. 除了计算返回值

如果这个定义是正确的,我的函数是一个纯函数吗?或者,我的理解是什么定义了一个纯函数是不正确的?

解决方案

不,不是。给定相同的输入,该函数将返回不同的值。然后你不能建立一个'表'来映射输入和输出。



从维基百科的文章纯函数
$ b


函数总是评估相同的结果值给出相同的
参数值(s)。函数结果值不能取决于任何
隐藏信息或状态,这些信息或状态可能在程序执行$ ​​b $ b进行时或在程序的不同执行之间发生变化,也不能依赖于来自I / O设备

此外,还有一件事情是,一个纯函数可以用一个代表输入和输出映射的表来代替,如此主题所述。



如果您想重写此函数并将其更改为纯函数,则您应该将该随机值作为参数传递。

 <$ c $函数测试(random,min,max){
return random *(max - min)+ min;
}

然后以此方式调用它(例如,以2和5为最小值,最大):

  test(Math.random(),2,5)


Is the following a pure function?

function test(min,max) {
   return  Math.random() * (max - min) + min;
}

My understanding is that a pure function follows these conditions:

  1. It returns a value computed from the parameters
  2. It doesn't do any work other than calculating the return value

If this definition is correct, is my function a pure function? Or is my understanding of what defines a pure function incorrect?

解决方案

No, it's not. Given the same input, this function will return different values. And then you can't build a 'table' that maps the input and the outputs.

From the Wikipedia article for Pure function:

The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices

Also, another thing is that a pure function can be replaced with a table which represents the mapping from the input and output, as explained in this thread.

If you want to rewrite this function and change it to a pure function, you should pass the random value as an argument too

function test(random, min, max) {
   return random * (max - min) + min;
}

and then call it this way (example, with 2 and 5 as min and max):

test( Math.random(), 2, 5)

这篇关于是一个调用Math.random()纯函数的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆