gpt4 book ai didi

algorithm - 有没有一种算法可以将一个数字分成三部分,并使它们的总和与原始数字相匹配?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:30:00 26 4
gpt4 key购买 nike

例如,如果您考虑以下示例。

100.00 - Original Number
33.33 - 1st divided by 3
33.33 - 2nd divided by 3
33.33 - 3rd divided by 3
99.99 - Is the sum of the 3 division outcomes

But i want it to match the original 100.00

我看到的一种方法是将原始数字减去前两个部分,结果将是我的第三个数字。现在,如果我取这 3 个数字,我就会得到我原来的数字。

 100.00 - Original Number
33.33 - 1st divided by 3
33.33 - 2nd divided by 3
33.34 - 3rd number
100.00 - Which gives me my original number correctly. (33.33+33.33+33.34 = 100.00)

在 Oracle PL/SQL 中是否有一个公式或一个函数或可以实现的东西?

提前致谢!

最佳答案

此版本也将精度作为参数:

with q as (select 100 as val, 3 as parts, 2 as prec from dual)
select rownum as no
,case when rownum = parts
then val - round(val / parts, prec) * (parts - 1)
else round(val / parts, prec)
end v
from q
connect by level <= parts

no v
=== =====
1 33.33
2 33.33
3 33.34

例如,如果您想将值拆分为当月的天数,您可以这样做:

with q as (select 100 as val
,extract(day from last_day(sysdate)) as parts
,2 as prec from dual)
select rownum as no
,case when rownum = parts
then val - round(val / parts, prec) * (parts - 1)
else round(val / parts, prec)
end v
from q
connect by level <= parts;

1 3.33
2 3.33
3 3.33
4 3.33
...
27 3.33
28 3.33
29 3.33
30 3.43

要按每个月的天数加权在每个月之间分配值,您可以改为这样做(更改 level <= 3 以更改计算的月数):

with q as (
select add_months(date '2013-07-01', rownum-1) the_month
,extract(day from last_day(add_months(date '2013-07-01', rownum-1)))
as days_in_month
,100 as val
,2 as prec
from dual
connect by level <= 3)
,q2 as (
select the_month, val, prec
,round(val * days_in_month
/ sum(days_in_month) over (), prec)
as apportioned
,row_number() over (order by the_month desc)
as reverse_rn
from q)
select the_month
,case when reverse_rn = 1
then val - sum(apportioned) over (order by the_month
rows between unbounded preceding and 1 preceding)
else apportioned
end as portion
from q2;

01/JUL/13 33.7
01/AUG/13 33.7
01/SEP/13 32.6

关于algorithm - 有没有一种算法可以将一个数字分成三部分,并使它们的总和与原始数字相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22026226/

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