Getting Unexpected Result in Python in Multiplication

Question:

I Made a program to multiply two large numbers but did,nt get expected result

When I Use My Program Result("1131231231231231232132176453243264237453265745327432747324575342321321321324234234324234243242343213","3242342342342342343243212341234")

I Got 3667838920001082329580291288441145791080382201626879559138562006502209700363203527339095217292763913228365618564468855268114011142

But When I Directly multiply these numbers in python i get
1131231231231231232132176453243264237453265745327432747324575342321321321324234234324234243242343213 * 3242342342342342343243212341234

3667838920001082167184590525973693204469083965208483826796404950051845708090751087384204216926015556670850912511772595077899944842

Both are Different.

def Result(val1,val2):
    array = []
    offset = "1"
    for x in range(len(val1)-1,-1,-1):
        result = MultiplyTwoNum(val1[x], val2)
        result = MultiplyTwoNum(offset, result)
        offset = MultiplyTwoNum("10", offset)
        array.append(result)
        #print(result)
    return array
def MultiplyTwoNum(VAL1,VAL2):
    Val1Int = int(VAL1)
    #print(Val1Int)
    ValResult = ""
    ValCarry = 0
    FinalResult = ""
    for i in range(len(VAL2)-1,-1,-1):
        Val2Int = int(VAL2[i])
        ValResult = (Val1Int * Val2Int)+ValCarry
        ValLeftValue = ValResult%10
        ValCarry = int(ValResult/10)
        FinalResult = str(ValLeftValue) + FinalResult
        if i == 0:
            FinalResult = str(ValCarry) + FinalResult
    return FinalResult
num = Result(Num1,Num2)
r = 0
for i in num:
  r = r + num
print(r)
Asked By: Risen_Star

||

Answers:

This innocent-looking expression:

int(ValResult/10)

Is wrong.

Judging by the int() around the division, you already know that division between two integers yields a float in Python 3. But putting int() around it doesn’t work, it’s too late, the damage has been done: ValResult has already been converted to a float, potentially rounding it. It’s a solution that seems to work when tested with small values (which do not get rounded when converted to a float), but it does not hold up under serious use.

Use integer division:

ValResult // 10

If I make that change in your code, the right result comes out, at least for the specific numbers in the question.


Perhaps it was intended that ValResult would always be small, in which case int(ValResult/10) is somewhat reasonable (but you may as well write ValResult // 10 anyway). However, it does not work out like that. ValResult indeed can be a large number, due to MultiplyTwoNum(offset, result), where offset may be a large power of ten.

Answered By: harold