将实数拆分为2个加数

2024-09-29 23:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

作为我对this question答案的扩展,我试图将一个实数拆分成两个数的最后一位相差atmost1(受浮点算术表示的限制)。在

例如:

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

为了澄清,结果加数必须包含与原始数字相同的位数。在

这就是我目前所想到的。在

目前为止,这适用于整数和小数点后有一位小数的数字。我相信一般的解决方法是计算出点后出现了多少个数字。在

我不知道该怎么做,但我相信一个解决方案是转换成字符串,在'.'上拆分,找到数字计数,然后乘以/除以10的适当幂。。。基本上扩展了我写的代码,所以它适用于任意数字。在

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


Tags: orand答案is数字算术解决方案this
2条回答

很快就搞定了,它符合你的需要吗?在

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))

和13;
和13;

或者使用ECMAScript 2016:

和13;

和13;

我想把小数点和小数点的位数转换成同样的数字。在

下面是一个python示例:

import math

def split_num(num):
    i = 0
    while (num != round(num, i)):  ## NOTE: guaranteed to terminate
        i = i + 1
    p1 = math.ceil( ( 10**i * num ) / 2) / 10**i  ## using 10**i rounds to the appropriate decimal place
    return (p1, num - p1)

## test output
if __name__ == "__main__":
    print(split_num(10))
    print(split_num(10.1))
    print(split_num(10.12))
    print(split_num(10.123))
    print(split_num(10.1234))
    print(split_num(7.3))

>>> python split_num.py
(5.0, 5.0)
(5.1, 5.0)
(5.06, 5.06)
(5.062, 5.060999999999999)
(5.0617, 5.0617)
(3.7, 3.5999999999999996)

相关问题 更多 >

    热门问题