php取正负5之间的随机数,js取正负随机数

今天写动态流星雨的时候有用到正负随机数这种东西,因为js的随机数的取值范围是[0,1)之间,而需求的区间需要[-100,200)之间,一时间犯了难,想不起来怎么取负数。就查阅了一下大家的做法。这里做个笔记,把需求和变式都整理一下。

1、取[0,10) 和 (0,10]

基础变式,区别在于取整的方式。

向下取整 Math.floor(Math.random() * 10) // [0,10)

向上取整 Math.ceil(Math.random() * 10) // (0,10]

2、取[0,10]

跟第一个不同,因为Math.random()的取值范围是左闭右开,所以他直接乘以10是取不到10的,这里稍微改一下

向下取整 Math.floor(Math.random() * 11) // [0,10]

向上取整 Math.ceil(Math.random() * 11) - 1 // [0,10]

3、取[10,20)和[10,20]

Math.floor(Math.random() * 10 ) + 10 // [10,20)

Math.floor((Math.random() + 1) * 10 ) // [10,20)

Math.floor(Math.random() * 11 ) + 10 // [10,20]

Math.floor((Math.random() + 1) * 11 ) // [11,20]注意这种方式是取不到10的

4、取[-5,5)

Math.floor(Math.random() * 10) - 5 // [-5,5)

Math.floor((Math.random() - 0.5) * 10 ) // [-5,5)

5、取[-3,10)

Math.floor(Math.random() * 13) - 3 // [-3,10)

总结一下,随机数取值的公式应该是:

Math.random() * ( |max| + |min|) + min // [ min , max ) max为最大值,min为最小值

最后,我能想到的变式就这些,如果有什么错误或者缺漏的,请告诉我,我会马上更新上来。

文章来源: blog.csdn.net,作者:Adolph_zgn,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/Adolph_zgn/article/details/112675608

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值