javascript - 如何验证十进制数是否在序列 0.001、0.002、...、2.048 中
问题描述
对于整数 [1, 2, 4, 8, 16, ...] 我可以使用这个函数:
const validate = num => (num & num - 1) == 0;
有没有一种优雅的类似方法可以在不使用循环的情况下使用十进制数?
- 0.001
- 0.002
- 0.004
- ...
- 2.048
并且应该可以使用基于初始值的小数点后的任意位数。
- 0.0001(初始值)
- 0.0002
- 0.0004
- 0.0016
- ...
- 1.6384
现在我使用该函数来确定小数点逗号后是否有数字并计算它们:
countDecimals(num) {
if (Math.floor(num.valueOf()) === num.valueOf()) return 0;
return num.toString().split(".")[1].length || 0;
}
然后我使用它:
validateEntryValue(entryValue) {
const decimalsQuantity = this.countDecimals(entryValue);
if (decimalsQuantity) {
const numToMul = Math.pow(10, decimalsQuantity);
return ((entryValue * numToMul) & (entryValue * numToMul) - 1) == 0;
}
return (entryValue & entryValue - 1) == 0;
}
但有些结果值未能通过测试:
- 0.001(初始值)
- 0.002
- 0.004
- 0.016
- 0.02 (不应验证,因为初始值不是 0.01)
解决方案
请注意,使用浮点数进行数学运算可能不准确,因此验证它们(需要精确值)可能效果不佳。
因此,您可以将数字相乘,使其成为整数,以避免精度问题,然后您甚至可以在其上使用您的解决方案。
这是一个纯粹的数学解决方案:
const validate = (toVerify, initial) => {
const num = toVerify / initial //division is like multiplication with the reciprocal!
return (num & num - 1) == 0
};
console.log(validate(8, 1)) //true
console.log(validate(0.08, 0.01)) //true
console.log(validate(0.008, 0.001)) //true
console.log(validate(0.016, 0.001)) //true
console.log(validate(0.08, 0.001)) //false
推荐阅读
- c - 从不兼容的指针类型初始化 - C 结构
- python - 如何限制 LSTM 的词汇量?
- spring-mvc - 如何在 tymeleaf 布局装饰器中添加页面特定的脚本标签?
- python - 如何在 PyQt5 中制作彩色 QTextEdit
- ruby-on-rails - 如何测试模型实例方法?
- reactjs - 彩色标签的样式化组件
- always-encrypted - 我正在尝试在未用于分区表的列上的分区表上实现始终加密
- php - php中floatval的额外精度
- android - 错误:未编译的 PNG 文件作为参数传递。必须先编译成 .flat 文件
- javascript - 为什么这等于 True 并因此在 React 中渲染一个 div?