-2

I am using a Cantor pairing function that takes two real number output unique real number.

def cantor_paring(a,b):
    return (1/2)*(a+b)*(a+b+1) + b

This work good for me when the input pair number are small.

cantor_paring(3,5)
41.0

However, when the input pair number is big the output becomes very huge.

cantor_paring(195149767,9877)
1.9043643420693068e+16

Now question I have is, is there a way to tweak the pair function so that output is relatively small even for big input numbers.

shakthydoss
  • 2,551
  • 6
  • 27
  • 36
  • Using the Cantor pairing function with floats seems a mistake, and large numbers are unavoidable. You'd better tell us what you use it for. –  Aug 23 '20 at 06:53
  • A single number does not become anything, including exponential. You seem to be using Python (tell or tag!): the standard number representation changes to "exponential" for numbers big or small enough. – greybeard Aug 23 '20 at 09:52
  • its quadratic not exponential.. (a^2 not n^a) but still big. :) this would not be an issue if your results were integer the only reason you are getting a floating point number is because of the 1/2. from the definition of the canter_paring from wiki and other it is a function from N x N - > N (integer numbers) so you need to keep things integers. if this is python 3. (which from the results is looks like it is) use // instead. so: return ((a+b)*(a+b+1))//2 + b And you will not have any issue with size as python will allow infinite digit int. – Rob Aug 23 '20 at 11:41

3 Answers3

1

Cantor pairing does not work for floats due to float precision limitations, because:

  • some different pairs might give the same result
  • retrieving a, b might give values distinct from former ones

For integers (including long arithmetics) you have to use

return (a+b)*(a+b+1) // 2 + b
MBo
  • 77,366
  • 5
  • 53
  • 86
0

For any input your function satisfies abs(cantor_pairing(a, b)) = O(max(a^2, b^2)). So by taking the third root of cantor_pairing(a, b) the limit would be max(abs(a)^(2/3), abs(b)^(2/3)) = O(max(abs(a), abs(b)). Since the third root is bijective for real numbers, uniqueness will be preserved as far as it is guaranteed by cantor_pairing. Alternatively you could use pretty much any other odd-numbered root.

0
  1. the function is not "exponential", it is quadratic.

  2. what you are asking is not possible. You want a function that returns a unique number for the n² pairs (a, b), so it takes n² distinct integers to achieve that whatever the encoding.

  3. doing this with floats does not make much sense.