Search code examples
pythonencodingdivisionmultiplicationdecoding

Simple multiplication and division being wildly inaccurate


tldr: The formula x / (1 * 1) subtracts hundreds of trillions. why?

Hey everyone! I am pretty new to python and while making a python message encrypter from scratch, (I know, there are easier ways of making message encoders. I am just making it for experience and fun) very simple multiplication and division problems seem to be wildly inaccurate. Basically, my encoder works by converting all the characters in the inputed string into numbers, then multiplying the number by two separate user-provided keys. I have been testing with all the keys set to 1, and the encoding works fine; decoding is the problem. My formula is:

Encoding:

String = String * Key1 * Key2     #Both keys are set to 1

Decoding:

String = String / (Key1 * Key2)     #Again, both keys are set to 1, so in theory it should just spit the string back out.

When I input 370190160220170180330190140310320, I get 370190160220170177391212613337088.

370190160220170180330190140310320

370190160220170177391212613337088

So a formula equivalent to x / (1 * 1) apparently means subtract however many quadrillions that is. Whats going on here? Like I said, I am a pretty new to python, so the solution to this problem might be insanely simple, but I just can't figure it out.


Solution

  • float division (/) isn't arbitrarily precise. int division (//) is, however!

    Try this out:

    assert 370190160220170180330190140310320 == 370190160220170180330190140310320 // 1
    assert 370190160220170180330190140310320 != 370190160220170180330190140310320 / 1
    

    For what you're doing you probably want to be using // and % rather than /!