fixed_point.py 940 B

1234567891011121314151617181920
  1. # This module defines the conversion functions from float <> int,
  2. # so that we can use floats in TinySMPC.
  3. from .finite_ring import MAX_INT64, MIN_INT64
  4. PRECISION = 8
  5. MAX_FLOAT = MAX_INT64 / 10**PRECISION # 92233720368.54776 (floats must be <, not <= this value, due to precision issues)
  6. MIN_FLOAT = MIN_INT64 / 10**PRECISION # -92233720368.54776 (floats must be >, not >= this value, due to precision issues)
  7. def fixed_point(fl):
  8. '''Converts a float to an fixed point int, with PRECISION decimal points of precision.'''
  9. assert MIN_FLOAT < fl < MAX_FLOAT
  10. return int(fl * 10**PRECISION)
  11. def float_point(n, n_mults=0):
  12. '''Converts a fixed point integer to a float.
  13. n_mults is the number of multiplications that generated the int, since multiplications
  14. of fixed point integers will accumulate extra scaling factors.'''
  15. scale_factor = (10**PRECISION)**n_mults
  16. return n / 10**PRECISION / scale_factor