gpt4 book ai didi

javascript - 将实数拆分为 2 个加数

转载 作者:行者123 更新时间:2023-11-30 15:10:00 25 4
gpt4 key购买 nike

作为我对 this question 的回答的延伸,我试图以这样的方式拆分一个实数,即两个数字中的每一个在最后一位数字上相差最多 1(受浮点算术表示的限制)。

例如:

7     => 4, 3
7.2 => 3.6, 3.6
7.3 => 3.7, 3.6 (or 3.5999999999999996) -- I understand this is a corner case and it is alright
7.25 => 3.63, 3.62
7.225 => 3.613, 3.612

需要说明的是,生成的加数必须包含与原始数字相同的位数。

这是我到目前为止想出的。

var x = 7.3;

if(x != Math.round(x)) {
var p1 = Math.ceil((x / 2) * 10) / 10;
} else {
var p1 = Math.ceil(x / 2);
}
var p2 = x - p1;

console.log(p1, p2);

截至目前,这适用于整数和小数点后一位小数我相信一般的解决方案将涉及弄清楚点后出现多少位数字。

我不确定如何做到这一点,但我相信一种解决方案是转换为字符串,在 '.' 上拆分,找到位数,然后乘以/除以适当的10 的幂...基本上扩展了我编写的代码,因此它适用于任意数字。

首选 Javascript 解决方案,但 python 解决方案也可以。任何帮助,将不胜感激。谢谢!

最佳答案

快速完成,它是否符合您的需求?

function GenerateAddends(n){
if(n == Math.round(n)){
return [Math.round(n/2),n-Math.round(n/2)];
}else{
var len = n.toString().split(".")[1].length
return [
Math.round(n/2 * Math.pow(10,len)) / Math.pow(10,len),
n - Math.round(n/2 * Math.pow(10,len)) / Math.pow(10,len)
]
}
}

console.log(GenerateAddends(7))
console.log(GenerateAddends(7.2))
console.log(GenerateAddends(7.3))
console.log(GenerateAddends(7.25))
console.log(GenerateAddends(7.225))

或者使用 ECMAScript 2016:

function GenerateAddends(n){
if(n == Math.round(n)){
return [Math.round(n/2),n-Math.round(n/2)];
}else{
var len = n.toString().split(".")[1].length
return [
Math.round(n/2 * 10**len) / 10**len,
n - Math.round(n/2 * 10**len) / 10**len
]
}
}

console.log(GenerateAddends(7))
console.log(GenerateAddends(7.2))
console.log(GenerateAddends(7.3))
console.log(GenerateAddends(7.25))
console.log(GenerateAddends(7.225))

你会发现,我和你的想法是一样的,转成字符串,得到小数位数。

关于javascript - 将实数拆分为 2 个加数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45246600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com