python-paillier icon indicating copy to clipboard operation
python-paillier copied to clipboard

Dealing with float numbers

Open SpBossGui opened this issue 5 years ago • 3 comments

I wonder whether it has the ability to deal with float numbers. Actually I run alternative_base.py in examples folder and changed the values of a and b to float numbers and it turned to be a failure to deal with it. Did I make any mistakes or could it really not? Thank you for answering my questions!

def math_example():
    print("Encoding two large positive numbers. BASE={}".format(ExampleEncodedNumber.BASE))

    a = 0.5
    b = 0.2

    encoded_a = ExampleEncodedNumber.encode(public_key, a)
    encoded_b = ExampleEncodedNumber.encode(public_key, b)

    print("Checking that decoding gives the same number...")
    assert a == encoded_a.decode()
    assert b == encoded_b.decode()

    print("Encrypting the encoded numbers")
    encrypted_a = public_key.encrypt(encoded_a)
    encrypted_b = public_key.encrypt(encoded_b)

    print("Adding the encrypted numbers")
    encrypted_c = encrypted_a + encrypted_b

    print("Decrypting the one encrypted sum")
    decrypted_but_encoded = \
        private_key.decrypt_encoded(encrypted_c, ExampleEncodedNumber)

    print("Checking the decrypted number is what we started with")

    print("Decrypted: {}".format(decrypted_but_encoded.decode()))

Generating paillier keypair Encoding a large positive number. With a BASE 64 encoding scheme Checking that decoding gives the same number... Encrypting the encoded number Decrypting... Checking the decrypted number is what we started with Encoding two large positive numbers. BASE=64 Checking that decoding gives the same number... Encrypting the encoded numbers Adding the encrypted numbers Decrypting the one encrypted sum Checking the decrypted number is what we started with Decrypted: 0.325

SpBossGui avatar Apr 21 '19 10:04 SpBossGui

You discovered a bug. Congratulations. In general, arithmetic with floating point numbers is fine. We have tests for that... However, changing the BASE changes everything. There is bug in how an encrypted number handles non-standard bases which leads to the problem you are seeing.

If you run you code again with the default BASE=16, then the results will be correct. I've also created issue #76 for the bug with the custom base.

wilko77 avatar Apr 29 '19 08:04 wilko77

It really helps, thank you very much!

SpBossGui avatar May 08 '19 08:05 SpBossGui

Hello, I would like to ask a question. Is it possible to get the result of operations with a determined number of decimal places during the float numbers operation? For example, in calculating E(10) / 3 = a, I want a result to be accurate to three decimal places, that is, D(a)=3.333 instead of 3.33333333333.

pk, sk = paillier.generate_paillier_keypair(n_length=128)
a = pk.encrypt(10)
print("a/3: ",sk.decrypt(a/3))

a/3: 3.333333333333333

LittleDonkey7 avatar Jan 09 '22 08:01 LittleDonkey7