diff --git a/Numerics/src/FixedPoint/Math.qs b/Numerics/src/FixedPoint/Math.qs new file mode 100644 index 00000000000..32327a22339 --- /dev/null +++ b/Numerics/src/FixedPoint/Math.qs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Math { + open Microsoft.Quantum.Convert; + + /// # Summary + /// Returns the smallest representable number for specific fixed point dimensions. + /// + /// # Input + /// ## integerBits + /// Number of integer bits (including the sign bit). + /// ## fractionalBits + /// Number of fractional bits. + /// + /// # Remark + /// The value can be computed as $-2^{p-1}$, where $p$ is the number of integer bits. + function SmallestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { + return -PowD(2.0, IntAsDouble(integerBits - 1)); + } + + /// # Summary + /// Returns the largest representable number for specific fixed point dimensions. + /// + /// # Input + /// ## integerBits + /// Number of integer bits (including the sign bit). + /// ## fractionalBits + /// Number of fractional bits. + /// + /// # Remark + /// The value can be computed as $2^{p-1} - 2^{-q}$, where $p$ + /// is the number of integer bits and $q$ is the number of fractional bits. + function LargestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { + return PowD(2.0, IntAsDouble(integerBits - 1)) - PowD(2.0, -IntAsDouble(fractionalBits)); + } + +} diff --git a/Numerics/tests/FixedPointTests.qs b/Numerics/tests/FixedPointTests.qs index 48e774997cb..d32596e41f9 100644 --- a/Numerics/tests/FixedPointTests.qs +++ b/Numerics/tests/FixedPointTests.qs @@ -435,4 +435,16 @@ namespace Microsoft.Quantum.Tests { } } } + + @Test("QuantumSimulator") + operation TestFixedPointLimits() : Unit { + for numBits in 1..6 { + for integerBits in 0..numBits { + let fractionalBits = numBits - integerBits; + + NearEqualityFactD(SmallestFixedPoint(integerBits, fractionalBits), BoolArrayAsFixedPoint(integerBits, [false, size = numBits] w/ numBits - 1 <- true)); + NearEqualityFactD(LargestFixedPoint(integerBits, fractionalBits), BoolArrayAsFixedPoint(integerBits, [true, size = numBits] w/ numBits - 1 <- false)); + } + } + } }