utils.fixed_point module¶
This is module implementing fixed point numbers for python. For a motivation, description and some examples, we refer to the docstring of the FixedPoint class.
- class utils.fixed_point.FixedPoint(value, precision)[source]¶
Bases:
object
Outline:
Motivation
Description
Examples
Motivation
Encryption schemes generally work with (scaled) fixed-point numbers (or integers), while such numbers are represented by floating points in python. This causes a discrepancy between the number that is encrypted and the respective decryption. This results in difficulties, e.g., when you want a random additive plaintext mask. This module addresses that discrepancy and provides arbitrary-precision fixed-point numbers including simple arithmetic such as addition, subtraction, multiplication and comparison operators.
Description
A fixed-point number is defined by 2 integers:
value: an arbitrary-precision integer
precision: an integer indicating the position of the radix which separates the integer part from the fractional part (counting from the right)
Fixed-point numbers can be instantiated from strings, integers, floats and other fixed-points. using the class method FixedPoint.fxp.
Examples:
fxp(“10.001234”) -> value = 10001234 precision = 6 (this represents 10.001234)
fxp(“1234e-2”) -> value = 1234 precision = 2 (this represents 12.34)
fxp(42) -> value = 42 precision = 0 (this represents 42)
fxp(-123, 2) -> value = -12300 precision = 2 (this represents -123.00)
fxp(123.) -> value = 123 precision = 0 (This represents 123)
fxp(-1.23) -> value = -123 precision = 2 (this represents -1.23)
fxp(-0.123, 5) -> value = -12300 precision = 5 (this represents -0.12300)
fxp(1234e-2) -> value = 1234 precision = 2 (this represents 12.34)
- DEFAULT_FLOAT_PRECISION = 16¶
- __abs__()[source]¶
Function that returns a fixed point number that represents the absolute value of the fixed point number.
- Return type:
- Returns:
absolute value of the fixed point number
- __add__(other)[source]¶
Add another fixed point number (or type convertible to a fixed point number) to self.
- Parameters:
other (
object
) – a fixed pont number, integer, string or float- Return type:
- Returns:
The addition of self to other
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __bool__()[source]¶
Function that casts a fixed point object to a boolean.
- Return type:
bool
- Returns:
A bool representing whether the fixed point object is unequal to zero.
- __eq__(other)[source]¶
Function that determines whether the fixed point object is equal to another object. The other object does not have to be a fixed point object. Additionally, this is a ‘weak’ equality in the sense that we first cast the other object to a fixed point number if it is not already and then check for equality. The precision value does not need to be equal, as long as the calibrated fixed point objects are equal. For strong equality, use strong_eq.
For example:
fxp(“100.0”) == fxp(“100.0000”) -> True
fxp(“12.34”) == 12.34 -> True
fxp(“0.012”) == fxp(“0.01”) -> False
- Parameters:
other (
object
) – Fixed point object, integer, string or float- Return type:
bool
- Returns:
whether self and the other object are (weakly) equal
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __float__()[source]¶
Function that cases a fixed point object to a float. If the fixed point number is too large, the float might return an error.
- Return type:
float
- Returns:
A floating point number representing the fixed point object
- __ge__(other)[source]¶
Function that returns whether this fixed pont number is greater than or equal to another compatible data type instance.
- Parameters:
other (
object
) – fixed point number, integer, string or float- Return type:
bool
- Returns:
whether self is greater than or equal to the fixed point version of other
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __gt__(other)[source]¶
Function that returns whether this fixed pont number is greater than another compatible data type instance.
- Parameters:
other (
object
) – fixed point number, integer, string or float- Return type:
bool
- Returns:
whether self is greater than the fixed point version of other
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __init__(value, precision)[source]¶
Initialise the fixed point number.
- Parameters:
value (
int
) – The arbitrary-precision integer value representing the fixed point numberprecision (
int
) – The location of the radix, counting from the right
- __int__()[source]¶
Function that casts a fixed point object to an integer. The function uses rounding instead of downward truncation.
- Return type:
int
- Returns:
An integer representing the rounded fixed point object
- __le__(other)[source]¶
Function that returns whether this fixed pont number is less than or equal to another compatible data type instance.
- Parameters:
other (
object
) – fixed point number, integer, string or float- Return type:
bool
- Returns:
whether self is less than or equal to the fixed point version of other
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __lshift__(other)[source]¶
Left bit shift operation without moving the radix. Shifts the underlying integer value, but does not modify the radix position
- Parameters:
other (
int
) – number of bits to shift- Return type:
- Returns:
shifted fixed point
- __lt__(other)[source]¶
Function that returns whether this fixed pont number is less than another compatible data type instance.
- Parameters:
other (
object
) – fixed point number, integer, string or float- Return type:
bool
- Returns:
whether self is less than the fixed point version of other
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __mul__(other)[source]¶
Multiply another fixed point number (or type convertible to a fixed point number) with self. Note that the result is calculated first with arbitrary precision and then rounded to obtain the maximum precision of the two inputs.
For example:
fxp(“0.1”) * fxp(“0.5”) = fxp(“0.1”)
fxp(“0.1”) * fxp(“0.4”) = fxp(“0.0”)
- Parameters:
other (
object
) – a fixed point number or other type convertible to a fixed point number.- Return type:
- Returns:
a * b
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __neg__()[source]¶
Function that returns a fixed point number that represents the negation of the fixed point number.
- Return type:
- Returns:
negation of the fixed point number
- __radd__(other)¶
Add another fixed point number (or type convertible to a fixed point number) to self.
- Parameters:
other (
object
) – a fixed pont number, integer, string or float- Return type:
- Returns:
The addition of self to other
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __repr__()[source]¶
Function that determines the representation of a fixed point object
- Return type:
str
- Returns:
string containing a representation of the fixed point object
- __rmul__(other)¶
Multiply another fixed point number (or type convertible to a fixed point number) with self. Note that the result is calculated first with arbitrary precision and then rounded to obtain the maximum precision of the two inputs.
For example:
fxp(“0.1”) * fxp(“0.5”) = fxp(“0.1”)
fxp(“0.1”) * fxp(“0.4”) = fxp(“0.0”)
- Parameters:
other (
object
) – a fixed point number or other type convertible to a fixed point number.- Return type:
- Returns:
a * b
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __rshift__(other)[source]¶
Right bit shift operation without moving the radix. Shifts the underlying integer value, but does not modify the radix position.
- Parameters:
other (
int
) – number of bits to shift- Return type:
- Returns:
shifted fixed point
- __rsub__(other)[source]¶
Subtract self from an object of a type convertible to a fixed point number
- Parameters:
other (
object
) – a fixed point number, integer, string or float- Return type:
- Returns:
the result of subtracting self from the other value
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __rtruediv__(other)[source]¶
Divide self with another fixed point number (or type convertible to a fixed point number). Note that the result is calculated first with arbitrary precision and then rounded to obtain the maximum precision of the two inputs.
For example:
fxp(“0.2”) / fxp(“3.0”) = fxp(“0.7”)
fxp(“0.1”) / fxp(“2.1”) = fxp(“0.0”)
- Parameters:
other (
object
) – a fixed point number or other type convertible to a fixed point number.- Return type:
- Returns:
a / b
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __str__()[source]¶
Function that casts a fixed point object to a string. First a representation without a radix is found and then the radix is inserted in the right place if the fixed point is not integer.
- Return type:
str
- Returns:
A string representing the fixed point object
- __sub__(other)[source]¶
Subtract another fixed point number (or type convertible to a fixed point number) from self.
- Parameters:
other (
object
) – a fixed point number, integer, string or float- Return type:
- Returns:
the result of subtracting the other value from self
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- __truediv__(other)[source]¶
Divide self with another fixed point number (or type convertible to a fixed point number). Note that the result is calculated first with arbitrary precision and then rounded to obtain the maximum precision of the two inputs.
For example:
fxp(“0.2”) / fxp(“3.0”) = fxp(“0.7”)
fxp(“0.1”) / fxp(“2.1”) = fxp(“0.0”)
- Parameters:
other (
object
) – a fixed point number or other type convertible to a fixed point number.- Return type:
- Returns:
a / b
- Raises:
NotImplementedError – If the other object does not have a compatible type.
- static calibrate(*fixed_points)[source]¶
Function that determines that maximum precision among all the fixed points and scales the fixed points according to the maximum precision.
- Parameters:
*fixed_points (
FixedPoint
) – fixed point numbers- Return type:
tuple
[int
,tuple
[FixedPoint
,...
]]- Returns:
A tuple where the first entry is the maximum precision and the subsequent entries are the given fixed points scaled to this maximum precision.
- static deserialize(obj, **_kwargs)[source]¶
Deserialization function for FixedPoint.
- Parameters:
obj (
dict
[str
,Any
]) – Object to deserialize.**_kwargs (
Any
) – Optional extra keyword arguments.
- Return type:
- Returns:
Deserialized FixedPoint instance.
- classmethod fxp(input_value, target_precision=None)[source]¶
Create a fixed-point number from a string, int, float or fixed-point number with a specified precision. If no precision is provided, it is deduced from the input_value. If precision is provided but it contradicts the precision of the input_value value (too large or too small), the input_value value is either truncated or trailing zeroes are added.
Legitimate input values:
- str: a string containing numbers in the range [0-9].
This can be point-separated to represent an integer part (before the full stop) and a fractional part (after the full stop).
- int: an arbitrarily large integer.
By default,it will be converted to a fixed-point with a precision of 0, but if a precision is provided, then the fixed point represents the input_value value times 10**-precision.
- float: a floating-point number.
The default precision is 16 bits. The floating point is scaled and the value is extracted according to the floating point number and the precision.
- FixedPoint: another fixed-point number.
If no precision is provided, all values are copied. If a precision is provided, the fixed-point number is either truncated or trailing zeroes are added to attain the new precision.
- Parameters:
input_value (
Union
[FixedPoint
,Integral
,str
,float
]) – the number to be converted to a fixed-point.target_precision (
int
|None
) – The desired precision of the resulting fixed-point number.
- Return type:
- Returns:
A fixed point version of the provided input
- Raises:
TypeError – Raised if the input value is not an integer, float, fixed point or string
- static initiate_from_float(input_value, target_precision=None)[source]¶
if the input value is a float, we multiply it by a power of 10 to create a scaled floating point number and then extract an integer to represent the fixed point number. If no precision is provided, the precision is extracted from the string representation.
- Parameters:
input_value (
float
) – the input_value integertarget_precision (
int
|None
) – desired precision
- Return type:
- Returns:
the resulting fixed-point number
- static initiate_from_fxp(input_value, target_precision=None)[source]¶
If the input value is another fixed point, correct the value with respect to the target precision.
- Parameters:
input_value (
FixedPoint
) – the input_value fixed-point numbertarget_precision (
int
|None
) – desired precision
- Return type:
- Returns:
the resulting fixed-point number
- static initiate_from_int(input_value, precision=None)[source]¶
If the input_value is an integer, we set the integer value to the input_value and decimal to zero.
- Parameters:
input_value (
Integral
) – the input_value integerprecision (
int
|None
) – position of the radix, counting from the right
- Return type:
- Returns:
the resulting fixed-point number
- static initiate_from_string(input_value, precision=None)[source]¶
This is the most reliable way to instantiate a fixed point, as the string accurately represents how the fixed point will be represented. The input is parsed as <integer>.<fractional> or <integer> or <integer>e<integer>. the precision is extracted automatically. If a target precision is provided then zeroes are added if the target precision is higher and the number is rounded towards the right precision if the target precision is lower.
- Parameters:
input_value (
str
) – string of decimals, possibly separated by a full stopprecision (
int
|None
) – desired precision. This has precedence over the implicit string precision.
- Return type:
- Returns:
the resulting fixed-point number
- Raises:
ValueError – Raised if the provided string does not fit the parsing format.
- precision:
int
¶
- static random_range(lower_bound, upper_bound, signed=False)[source]¶
Return a uniformly random fixed-point in the interval [lower_bound, upper_bound). If signed is True, the interval becomes [lower_bound, upper_bound) $cup$ (-upper_bound, lower_bound].
- Parameters:
lower_bound (
FixedPoint
) – integer lower bound (inclusive)upper_bound (
FixedPoint
) – integer upper bound (exclusive)signed (
bool
) – whether the random fixed-point number should have a random sign or just be positive
- Return type:
- Returns:
a uniformly random fixed-point in the specified interval
- static round_to_precision(value, current_precision, target_precision)[source]¶
Function that takes a fixed point representation (value, precision) and changes the value to obtain the right precision for the fixed point representation. It uses rounding when the target precision is lower than the current precision.
- Parameters:
value (
int
) – An integer representing the valuecurrent_precision (
int
) – An integer representing the precision of the given valuetarget_precision (
int
) – The desired precision
- Return type:
int
- Returns:
A new value that represents a (rounded) fixed point number with the target precision
- Raises:
TypeError – If value, current_precision or target_precision is not an int
- serialize(**_kwargs)[source]¶
Serialization function for FixedPoint.
- Parameters:
**_kwargs (
Any
) – Optional extra keyword arguments.- Return type:
dict
[str
,Any
]- Returns:
Serialized representation of the current object.
- static strong_eq(fxp_1, fxp_2)[source]¶
Function that determines whether two fixed points are exactly equal
- Parameters:
fxp_1 (
FixedPoint
) – Fixed point numberfxp_2 (
FixedPoint
) – Fixed point number
- Return type:
bool
- Returns:
Whether the values and precision of the fixed point objects are equal
- value:
int
¶