Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.

Commit 131a8e7

Browse files
msoekentcNickolas
andauthored
Add functions for smallest and largest representable fixed point (#606)
* Add functions for smallest and largest representable fixed point Implements #594 * New line. * Apply suggestions from code review Co-authored-by: Mariia Mykhailova <[email protected]> Co-authored-by: Mariia Mykhailova <[email protected]>
1 parent 3496411 commit 131a8e7

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

Numerics/src/FixedPoint/Math.qs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
namespace Microsoft.Quantum.Math {
5+
open Microsoft.Quantum.Convert;
6+
7+
/// # Summary
8+
/// Returns the smallest representable number for specific fixed point dimensions.
9+
///
10+
/// # Input
11+
/// ## integerBits
12+
/// Number of integer bits (including the sign bit).
13+
/// ## fractionalBits
14+
/// Number of fractional bits.
15+
///
16+
/// # Remark
17+
/// The value can be computed as $-2^{p-1}$, where $p$ is the number of integer bits.
18+
function SmallestFixedPoint(integerBits : Int, fractionalBits : Int) : Double {
19+
return -PowD(2.0, IntAsDouble(integerBits - 1));
20+
}
21+
22+
/// # Summary
23+
/// Returns the largest representable number for specific fixed point dimensions.
24+
///
25+
/// # Input
26+
/// ## integerBits
27+
/// Number of integer bits (including the sign bit).
28+
/// ## fractionalBits
29+
/// Number of fractional bits.
30+
///
31+
/// # Remark
32+
/// The value can be computed as $2^{p-1} - 2^{-q}$, where $p$
33+
/// is the number of integer bits and $q$ is the number of fractional bits.
34+
function LargestFixedPoint(integerBits : Int, fractionalBits : Int) : Double {
35+
return PowD(2.0, IntAsDouble(integerBits - 1)) - PowD(2.0, -IntAsDouble(fractionalBits));
36+
}
37+
38+
}

Numerics/tests/FixedPointTests.qs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,4 +435,16 @@ namespace Microsoft.Quantum.Tests {
435435
}
436436
}
437437
}
438+
439+
@Test("QuantumSimulator")
440+
operation TestFixedPointLimits() : Unit {
441+
for numBits in 1..6 {
442+
for integerBits in 0..numBits {
443+
let fractionalBits = numBits - integerBits;
444+
445+
NearEqualityFactD(SmallestFixedPoint(integerBits, fractionalBits), BoolArrayAsFixedPoint(integerBits, [false, size = numBits] w/ numBits - 1 <- true));
446+
NearEqualityFactD(LargestFixedPoint(integerBits, fractionalBits), BoolArrayAsFixedPoint(integerBits, [true, size = numBits] w/ numBits - 1 <- false));
447+
}
448+
}
449+
}
438450
}

0 commit comments

Comments
 (0)