使用对数以避免数值下溢的算术问题
我有两个分数列表;
说 A = [ 1/212, 5/212, 3/212, ... ]
和 B = [ 4/143, 7/143, 2/143, ... ]
。
如果我们定义 A' = a[0] * a[1] * a[2] * ...
和 B' = b[0] * b[1] * b[ 2] * ...
我想计算 A' / B'
的值,
我的麻烦是 A 和 B 都很长,而且每个值都很小,所以计算乘积会导致数值下溢非常快...
我知道通过对数将乘积转换为总和可以帮助我确定 A' 或 B' 哪个更大,
即 max( log(a[0])+log(a[1] )+..., log(b[0])+log(b[1])+... )
但我需要实际比率....
迄今为止我最好的选择是保留数字表示为分数,即 A = [ [1,212], [5,212], [3,212], ... ]
并实现我自己的算术,但它变得笨拙,我有一种感觉(简单)我只是缺少对数的方式......
A 和 B 的分子不是来自序列。出于这个问题的目的,它们也可能是随机的。如果它有帮助,A 中所有值的分母都相同,B 的所有分母也相同。
欢迎任何想法!
垫
I have two lists of fractions;
say A = [ 1/212, 5/212, 3/212, ... ]
and B = [ 4/143, 7/143, 2/143, ... ]
.
If we define A' = a[0] * a[1] * a[2] * ...
and B' = b[0] * b[1] * b[2] * ...
I want to calculate the values of A' / B'
,
My trouble is A are B are both quite long and each value is small so calculating the product causes numerical underflow very quickly...
I understand turning the product into a sum through logarithms can help me determine which of A' or B' is greater
ie max( log(a[0])+log(a[1])+..., log(b[0])+log(b[1])+... )
but i need the actual ratio....
My best bet to date is to keep the number representations as fractions, ie A = [ [1,212], [5,212], [3,212], ... ]
and implement my own arithmetic but it's getting clumsy and I have a feeling there is a (simple) way of logarithms I'm just missing....
The numerators for A and B don't come from a sequence. They might as well be random for the purpose of this question. If it helps the denominators for all values in A are the same, as are all the denominators for B.
Any ideas most welcome!
Mat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以用稍微不同的顺序来计算它:
You could calculate it in a slightly different order:
如果您想将其保留为对数,请记住 A/B 对应于 log A - log B,因此在将 A 和 B 的对数相加后,您可以通过对 log 求幂来找到较大值与较小值的比率以 max(logsumA, logsumB)-min(logsumA,logsumB) 为底。
If you want to keep it in logarithms, remember that A/B corresponds to log A - log B, so after you've summed the logarithms of A and B, you can find the ratio of the larger to the smaller by exponentiating your log base with max(logsumA, logsumB)-min(logsumA,logsumB).
去掉分子和分母,因为它们在整个序列中是相同的。逐个元素计算分子的比率(而不是像@Mark建议的那样),最后将结果乘以分母B/分母A的正确幂。
或者,如果这在计算分子的乘积或分母的幂时威胁到整数溢出,例如:
我可能有一些分数颠倒了,但我想你能弄清楚吗?
Strip out the numerators and denominators since they are the same for the whole sequence. Compute the ratio of numerators element-by-element (rather as @Mark suggests), finally multiply the result by the right power of the denominator-of-B/denominator-of-A.
Or, if that threatens integer overflow in computing the product of the numerators or powers of the denominators, something like:
I've probably got some of the fractions upside-down, but I guess you can figure that out ?