Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Numerics/src/FixedPoint/Math.qs
Original file line number Diff line number Diff line change
@@ -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));
}

}
12 changes: 12 additions & 0 deletions Numerics/tests/FixedPointTests.qs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
}
}