简体   繁体   English

python的四舍五入问题(实现唐津算法)

[英]Rounding issue with python (implementing Karatsuba's algorithm)

Having the hardest time figuring out rounding issue in my python code that is supposed to output the multiplied value of 2 numbers using Karatsuba's algorithm [ 1 , 2 ]. 具有使用Karatsuba算法应该输出2号的乘积值最困难的时候搞清楚在我的Python代码四舍五入问题[ 12 ]。 This is my code: 这是我的代码:

def mult(num1,num2): 
    if num1 < 10 or num2 < 10:
        return int(num1*num2)       
    else:
        n = len(str(num1))
        a = int(str(num1)[:-(int(n/2))])
        #print(a)
        c = int(str(num2)[:-(int(n/2))])
        #print(c)
        b = int(str(num1)[-(int(n/2)):])
        #print(b)
        d = int(str(num2)[-(int(n/2)):])
        #print(d)
        val1 = mult(a,c)
        val2 = mult(b,d)
        val3 = mult(a+b,c+d) - val1 - val2


        ans = val1*(10**int(n)) + val2 + (val3)*(10**(int(n/2)))

        return int(ans)

I will add any additional info needed, please let me know Any help in this regards is much appreciated Thank you 我将添加所需的任何其他信息,请让我知道这方面的任何帮助,谢谢

In found a working example of the Karatsuba algorithm: https://pythonandr.com/2015/10/13/karatsuba-multiplication-algorithm-python-code/ 在其中找到了Karatsuba算法的工作示例: https : //pythonandr.com/2015/10/13/karatsuba-multiplication-algorithm-python-code/

I think your problem is that you cannot handle odd n in this way. 我认为您的问题是您无法以这种方式处理奇数n。 For example multiplying 100 with 100: If you round 1.5 to 2 you get 100 000 a zero to much and if your round it to 1 your get 1000 with a zero missing. 例如,将100乘以100:如果将1.5舍入为2,则得到100000,零为零;如果舍入为1,则得到1000,而零为零。 Also you should take the max number of digits from both numbers not just num1. 另外,您应该从两个数字中获取最大位数,而不仅仅是num1。

I hope the code below can help you solving your problem: 希望以下代码可以帮助您解决问题:

def karatsuba(x,y):
    """Function to multiply 2 numbers in a more efficient manner than the grade school algorithm"""
    if len(str(x)) == 1 or len(str(y)) == 1:
        return x*y
    else:
        n = max(len(str(x)),len(str(y)))
        nby2 = n / 2

        a = x / 10**(nby2)
        b = x % 10**(nby2)
        c = y / 10**(nby2)
        d = y % 10**(nby2)

        ac = karatsuba(a,c)
        bd = karatsuba(b,d)
        ad_plus_bc = karatsuba(a+b,c+d) - ac - bd

            # this little trick, writing n as 2*nby2 takes care of both even and odd n
        prod = ac * 10**(2*nby2) + (ad_plus_bc * 10**nby2) + bd

        return prod

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM