n + Math.random()是否总是小于n + 1? [英] Is n+Math.random() always smaller than n+1?

查看:44
本文介绍了n + Math.random()是否总是小于n + 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Math.random()小于1,但是问题是Math.random()生成浮点数,并且浮点加法可能会有舍入错误.

I know Math.random() is smaller than 1, but the problem is, Math.random() generates floating point numbers, and floating point addition may have rounding errors.

所以我的问题是,n + Math.random()<是否有n的任何可能值?n + 1是假的吗?

So my question is, is there any possible value of n which n+Math.random() < n+1 is false?

推荐答案

最大的随机结果是严格小于1.0的最大double.将其加1得到的实数结果恰好介于2.0和小于2.0的最大倍数之间.四舍五入到最接近会把它四舍五入到2.0,因为它是平局,而2.0是偶数.

The largest random result is the largest double that is strictly less than 1.0. Adding one to it gets a real number result that is exactly half way between 2.0 and the largest double that is less than 2.0. Round to nearest will round it to 2.0, because it is a tie and 2.0 is even.

您需要允许n + Math.random()<由于舍入,n + 1为假.

You need to allow for n+Math.random() < n+1 being false due to rounding.

这篇关于n + Math.random()是否总是小于n + 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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