Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LibCrypto: Improve precision of BigFraction::to_double #3174

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
62 changes: 60 additions & 2 deletions Libraries/LibCrypto/BigFraction/BigFraction.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2022, Lucas Chollet <[email protected]>
* Copyright (c) 2025, Manuel Zahariev <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
Expand All @@ -8,7 +9,10 @@
#include <AK/ByteString.h>
#include <AK/Math.h>
#include <AK/StringBuilder.h>
#include <LibCrypto/BigInt/UnsignedBigInteger.h>
#include <LibCrypto/NumberTheory/ModularFunctions.h>
#include <cstddef>
#include <limits>

namespace Crypto {

Expand Down Expand Up @@ -134,10 +138,64 @@ BigFraction::BigFraction(double d)
m_numerator.set_to(negative ? (m_numerator.negated_value()) : m_numerator);
}

/*
* Complexity O(N), where N=total number of words in numerator and denominator:
* - shifts: O(N)
* - division: constant (fixed bound on size of shifted numerator and denominator
* - conversion to double: constant (64-bit quotient)
*/
double BigFraction::to_double() const
{
// FIXME: very naive implementation
return m_numerator.to_double() / m_denominator.to_double();
// 1. Shift the numerator and denominator so that:
// - the denominator is at most 64 bits
// - the numerator is exactly 64 bits larger than the denominator
size_t const bit_precision = 64; // divide the fraction to this precision
bool const sign = m_numerator.is_negative();

int denominator_right_shift = 0;

size_t bit_size_numerator = m_numerator.unsigned_value().one_based_index_of_highest_set_bit();
size_t bit_size_denominator = m_denominator.one_based_index_of_highest_set_bit();

if (bit_size_denominator > bit_precision) { // reduce precision of a large denominator
denominator_right_shift = bit_size_denominator - bit_precision;
bit_size_denominator = bit_precision;
}

int numerator_right_shift = bit_size_numerator - bit_size_denominator - bit_precision;

UnsignedBigInteger shifted_denominator = m_denominator.shift_right(denominator_right_shift);
UnsignedBigInteger shifted_numerator;
if (numerator_right_shift < 0)
shifted_numerator.set_to(m_numerator.unsigned_value().shift_left(-numerator_right_shift)); // increase numerator to increase precision
else
shifted_numerator.set_to(m_numerator.unsigned_value().shift_right(numerator_right_shift)); // decrease precision of numerator

// 2. Divide the shifted numerator to the shifted denominator. The result will have 64-bit precision.
// Then, convert the quotient to double.
double result = SignedBigInteger { shifted_numerator.divided_by(shifted_denominator).quotient, sign }.to_double();

// 3. Convert the result to a double, including the denominator/numerator shifts in the exponent.
using Extractor = FloatExtractor<double>;

Extractor double_extractor;
double_extractor.d = result;

int exponent = double_extractor.exponent + numerator_right_shift - denominator_right_shift;

if ((exponent < 0) && sign) // undeflow
return -0.0;
if (exponent < 0)
return +0.0;
if ((exponent > int(Extractor::exponent_max)) && sign) // overflow
return -std::numeric_limits<double>::infinity();
if (exponent > int(Extractor::exponent_max))
return std::numeric_limits<double>::infinity();

double_extractor.sign = sign;
double_extractor.exponent += (numerator_right_shift - denominator_right_shift);

return double_extractor.d;
}

bool BigFraction::is_zero() const
Expand Down
83 changes: 50 additions & 33 deletions Libraries/LibCrypto/BigInt/Algorithms/BitwiseOperations.cpp
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
/*
* Copyright (c) 2020, Itamar S. <[email protected]>
* Copyright (c) 2020-2021, Dex♪ <[email protected]>
* Copyright (c) 2025, Manuel Zahariev <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/

#include "UnsignedBigIntegerAlgorithms.h"
#include <AK/NumericLimits.h>
#include <LibCrypto/BigInt/UnsignedBigInteger.h>
#include <bitset>
#include <cstddef>

namespace Crypto {

Expand Down Expand Up @@ -161,59 +164,73 @@ FLATTEN void UnsignedBigIntegerAlgorithms::bitwise_not_fill_to_one_based_index_w
}

/**
* Complexity : O(N + num_bits % 8) where N is the number of words in the number
* Shift method :
* Start by shifting by whole words in num_bits (by putting missing words at the start),
* then shift the number's words two by two by the remaining amount of bits.
* Complexity : O(N) where N is the number of words in the number
*/
FLATTEN void UnsignedBigIntegerAlgorithms::shift_left_without_allocation(
UnsignedBigInteger const& number,
size_t num_bits,
UnsignedBigInteger& temp_result,
UnsignedBigInteger& temp_plus,
UnsignedBigInteger& output)
{
// We can only do shift operations on individual words
// where the shift amount is <= size of word (32).
// But we do know how to shift by a multiple of word size (e.g 64=32*2)
// So we first shift the result by how many whole words fit in 'num_bits'
shift_left_by_n_words(number, num_bits / UnsignedBigInteger::BITS_IN_WORD, temp_result);
size_t const bit_shift = num_bits % UnsignedBigInteger::BITS_IN_WORD;
size_t const bit_shift_complement = UnsignedBigInteger::BITS_IN_WORD - bit_shift;

output.set_to(temp_result);
// true if the high word is a result of the bit_shift
bool const hiword_shift = (bit_shift + ((number.one_based_index_of_highest_set_bit() - 1) % UnsignedBigInteger::BITS_IN_WORD) >= UnsignedBigInteger::BITS_IN_WORD);
size_t const word_shift = num_bits / UnsignedBigInteger::BITS_IN_WORD;

// And now we shift by the leftover amount of bits
num_bits %= UnsignedBigInteger::BITS_IN_WORD;
shift_left_by_n_words(number, word_shift + (hiword_shift ? 1 : 0), output);

if (num_bits == 0) {
if (bit_shift == 0) // shifting left by an exact number of words)
return;
}

for (size_t i = 0; i < temp_result.length(); ++i) {
u32 current_word_of_temp_result = shift_left_get_one_word(temp_result, num_bits, i);
output.m_words[i] = current_word_of_temp_result;
}
UnsignedBigInteger::Word carry { 0 };
for (size_t i = 0; i < number.length(); ++i) {
size_t const output_index = i + word_shift;

// Shifting the last word can produce a carry
u32 carry_word = shift_left_get_one_word(temp_result, num_bits, temp_result.length());
if (carry_word != 0) {

// output += (carry_word << temp_result.length())
// FIXME : Using temp_plus this way to transform carry_word into a bigint is not
// efficient nor pretty. Maybe we should have an "add_with_shift" method ?
temp_plus.set_to_0();
temp_plus.m_words.append(carry_word);
shift_left_by_n_words(temp_plus, temp_result.length(), temp_result);
add_into_accumulator_without_allocation(output, temp_result);
output.m_words[output_index] = (number.m_words.at(i) << bit_shift) | carry;
carry = (number.m_words.at(i) >> bit_shift_complement);
}

if (hiword_shift)
output.m_words[output.length() - 1] = carry;
}

/**
* Complexity : O(N) where N is the number of words in the number
*/
FLATTEN void UnsignedBigIntegerAlgorithms::shift_right_without_allocation(
UnsignedBigInteger const& number,
size_t num_bits,
UnsignedBigInteger& output)
{
output.m_words.resize_and_keep_capacity(number.length() - (num_bits / UnsignedBigInteger::BITS_IN_WORD));
Ops::shift_right(number.words_span(), num_bits, output.words_span());
size_t const bit_shift = num_bits % UnsignedBigInteger::BITS_IN_WORD;
size_t const bit_shift_complement = UnsignedBigInteger::BITS_IN_WORD - bit_shift;

// true if the high word will be zeroed as a result of the shift
bool const hiword_zero = (bit_shift > ((number.one_based_index_of_highest_set_bit() - 1) % UnsignedBigInteger::BITS_IN_WORD));
size_t const word_shift = num_bits / UnsignedBigInteger::BITS_IN_WORD + (hiword_zero ? 1 : 0);

if (word_shift >= number.length()) // all non-zero digits have been shifted right; result is zero
return;

shift_right_by_n_words(number, word_shift, output);

if (bit_shift == 0) // shifting right by an exact number of words)
return;

size_t const output_length = output.length();
size_t number_index = number.length() - 1;
UnsignedBigInteger::Word carry { hiword_zero ? (number.words().at(number_index) << bit_shift_complement) : 0 };
if (hiword_zero)
--number_index;

for (size_t i = 0; i < output_length; ++i) {
size_t const output_index = output_length - i - 1; // downto index 0

output.m_words[output_index] = ((number.m_words.at(number_index) >> bit_shift)) | carry;
carry = (number.m_words.at(number_index) << bit_shift_complement);
--number_index;
}
}

void UnsignedBigIntegerAlgorithms::shift_left_by_n_words(
Expand Down
8 changes: 3 additions & 5 deletions Libraries/LibCrypto/BigInt/Algorithms/GCD.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ void UnsignedBigIntegerAlgorithms::extended_GCD_without_allocation(
UnsignedBigInteger& temp_quotient,
UnsignedBigInteger& temp_1,
UnsignedBigInteger& temp_2,
UnsignedBigInteger& temp_shift_result,
UnsignedBigInteger& temp_shift_plus,
UnsignedBigInteger& temp_shift,
UnsignedBigInteger& temp_r,
UnsignedBigInteger& temp_s,
Expand All @@ -66,7 +64,7 @@ void UnsignedBigIntegerAlgorithms::extended_GCD_without_allocation(
divide_without_allocation(gcd, temp_r, temp_quotient, temp_1);

temp_2.set_to(temp_r);
multiply_without_allocation(temp_quotient, temp_r, temp_shift_result, temp_shift_plus, temp_shift, temp_1);
multiply_without_allocation(temp_quotient, temp_r, temp_shift, temp_1);
while (gcd < temp_1) {
add_into_accumulator_without_allocation(gcd, b);
}
Expand All @@ -75,7 +73,7 @@ void UnsignedBigIntegerAlgorithms::extended_GCD_without_allocation(

// (old_s, s) := (s, old_s − quotient × s)
temp_2.set_to(temp_s);
multiply_without_allocation(temp_quotient, temp_s, temp_shift_result, temp_shift_plus, temp_shift, temp_1);
multiply_without_allocation(temp_quotient, temp_s, temp_shift, temp_1);
while (x < temp_1) {
add_into_accumulator_without_allocation(x, b);
}
Expand All @@ -84,7 +82,7 @@ void UnsignedBigIntegerAlgorithms::extended_GCD_without_allocation(

// (old_t, t) := (t, old_t − quotient × t)
temp_2.set_to(temp_t);
multiply_without_allocation(temp_quotient, temp_t, temp_shift_result, temp_shift_plus, temp_shift, temp_1);
multiply_without_allocation(temp_quotient, temp_t, temp_shift, temp_1);
while (y < temp_1) {
add_into_accumulator_without_allocation(y, b);
}
Expand Down
4 changes: 1 addition & 3 deletions Libraries/LibCrypto/BigInt/Algorithms/ModularInverse.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,12 @@ void UnsignedBigIntegerAlgorithms::modular_inverse_without_allocation(
UnsignedBigInteger& temp_quotient,
UnsignedBigInteger& temp_1,
UnsignedBigInteger& temp_2,
UnsignedBigInteger& temp_shift_result,
UnsignedBigInteger& temp_shift_plus,
UnsignedBigInteger& temp_shift,
UnsignedBigInteger& temp_r,
UnsignedBigInteger& temp_s,
UnsignedBigInteger& temp_t)
{
extended_GCD_without_allocation(a, b, result, temp_y, temp_gcd, temp_quotient, temp_1, temp_2, temp_shift_result, temp_shift_plus, temp_shift, temp_r, temp_s, temp_t);
extended_GCD_without_allocation(a, b, result, temp_y, temp_gcd, temp_quotient, temp_1, temp_2, temp_shift, temp_r, temp_s, temp_t);

divide_without_allocation(result, b, temp_quotient, temp_1);
add_into_accumulator_without_allocation(temp_1, b);
Expand Down
6 changes: 2 additions & 4 deletions Libraries/LibCrypto/BigInt/Algorithms/ModularPower.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ void UnsignedBigIntegerAlgorithms::destructive_modular_power_without_allocation(
UnsignedBigInteger& base,
UnsignedBigInteger const& m,
UnsignedBigInteger& temp_1,
UnsignedBigInteger& temp_2,
UnsignedBigInteger& temp_3,
UnsignedBigInteger& temp_multiply,
UnsignedBigInteger& temp_quotient,
UnsignedBigInteger& temp_remainder,
Expand All @@ -25,7 +23,7 @@ void UnsignedBigIntegerAlgorithms::destructive_modular_power_without_allocation(
while (!(ep < 1)) {
if (ep.words()[0] % 2 == 1) {
// exp = (exp * base) % m;
multiply_without_allocation(exp, base, temp_1, temp_2, temp_3, temp_multiply);
multiply_without_allocation(exp, base, temp_1, temp_multiply);
divide_without_allocation(temp_multiply, m, temp_quotient, temp_remainder);
exp.set_to(temp_remainder);
}
Expand All @@ -34,7 +32,7 @@ void UnsignedBigIntegerAlgorithms::destructive_modular_power_without_allocation(
ep.set_to(ep.shift_right(1));

// base = (base * base) % m;
multiply_without_allocation(base, base, temp_1, temp_2, temp_3, temp_multiply);
multiply_without_allocation(base, base, temp_1, temp_multiply);
divide_without_allocation(temp_multiply, m, temp_quotient, temp_remainder);
base.set_to(temp_remainder);

Expand Down
4 changes: 1 addition & 3 deletions Libraries/LibCrypto/BigInt/Algorithms/Multiplication.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ namespace Crypto {
FLATTEN void UnsignedBigIntegerAlgorithms::multiply_without_allocation(
UnsignedBigInteger const& left,
UnsignedBigInteger const& right,
UnsignedBigInteger& temp_shift_result,
UnsignedBigInteger& temp_shift_plus,
UnsignedBigInteger& temp_shift,
UnsignedBigInteger& output)
{
Expand All @@ -37,7 +35,7 @@ FLATTEN void UnsignedBigIntegerAlgorithms::multiply_without_allocation(
size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;

// output += (right << shift_amount);
shift_left_without_allocation(right, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
shift_left_without_allocation(right, shift_amount, temp_shift);
add_into_accumulator_without_allocation(output, temp_shift);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ class UnsignedBigIntegerAlgorithms {
static void bitwise_and_without_allocation(UnsignedBigInteger const& left, UnsignedBigInteger const& right, UnsignedBigInteger& output);
static void bitwise_xor_without_allocation(UnsignedBigInteger const& left, UnsignedBigInteger const& right, UnsignedBigInteger& output);
static void bitwise_not_fill_to_one_based_index_without_allocation(UnsignedBigInteger const& left, size_t, UnsignedBigInteger& output);
static void shift_left_without_allocation(UnsignedBigInteger const& number, size_t bits_to_shift_by, UnsignedBigInteger& temp_result, UnsignedBigInteger& temp_plus, UnsignedBigInteger& output);
static void shift_left_without_allocation(UnsignedBigInteger const& number, size_t bits_to_shift_by, UnsignedBigInteger& output);
static void shift_right_without_allocation(UnsignedBigInteger const& number, size_t num_bits, UnsignedBigInteger& output);
static void multiply_without_allocation(UnsignedBigInteger const& left, UnsignedBigInteger const& right, UnsignedBigInteger& temp_shift_result, UnsignedBigInteger& temp_shift_plus, UnsignedBigInteger& temp_shift, UnsignedBigInteger& output);
static void multiply_without_allocation(UnsignedBigInteger const& left, UnsignedBigInteger const& right, UnsignedBigInteger& temp_shift, UnsignedBigInteger& output);
static void divide_without_allocation(UnsignedBigInteger const& numerator, UnsignedBigInteger const& denominator, UnsignedBigInteger& quotient, UnsignedBigInteger& remainder);
static void divide_u16_without_allocation(UnsignedBigInteger const& numerator, UnsignedBigInteger::Word denominator, UnsignedBigInteger& quotient, UnsignedBigInteger& remainder);

static void extended_GCD_without_allocation(UnsignedBigInteger const& a, UnsignedBigInteger const& b, UnsignedBigInteger& x, UnsignedBigInteger& y, UnsignedBigInteger& gcd, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_2, UnsignedBigInteger& temp_shift_result, UnsignedBigInteger& temp_shift_plus, UnsignedBigInteger& temp_shift, UnsignedBigInteger& temp_r, UnsignedBigInteger& temp_s, UnsignedBigInteger& temp_t);
static void extended_GCD_without_allocation(UnsignedBigInteger const& a, UnsignedBigInteger const& b, UnsignedBigInteger& x, UnsignedBigInteger& y, UnsignedBigInteger& gcd, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_2, UnsignedBigInteger& temp_shift, UnsignedBigInteger& temp_r, UnsignedBigInteger& temp_s, UnsignedBigInteger& temp_t);
static void destructive_GCD_without_allocation(UnsignedBigInteger& temp_a, UnsignedBigInteger& temp_b, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_remainder, UnsignedBigInteger& output);
static void modular_inverse_without_allocation(UnsignedBigInteger const& a, UnsignedBigInteger const& b, UnsignedBigInteger& result, UnsignedBigInteger& temp_y, UnsignedBigInteger& temp_gcd, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_2, UnsignedBigInteger& temp_shift_result, UnsignedBigInteger& temp_shift_plus, UnsignedBigInteger& temp_shift, UnsignedBigInteger& temp_r, UnsignedBigInteger& temp_s, UnsignedBigInteger& temp_t);
static void destructive_modular_power_without_allocation(UnsignedBigInteger& ep, UnsignedBigInteger& base, UnsignedBigInteger const& m, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_2, UnsignedBigInteger& temp_3, UnsignedBigInteger& temp_multiply, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_remainder, UnsignedBigInteger& result);
static void modular_inverse_without_allocation(UnsignedBigInteger const& a, UnsignedBigInteger const& b, UnsignedBigInteger& result, UnsignedBigInteger& temp_y, UnsignedBigInteger& temp_gcd, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_2, UnsignedBigInteger& temp_shift, UnsignedBigInteger& temp_r, UnsignedBigInteger& temp_s, UnsignedBigInteger& temp_t);
static void destructive_modular_power_without_allocation(UnsignedBigInteger& ep, UnsignedBigInteger& base, UnsignedBigInteger const& m, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_multiply, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_remainder, UnsignedBigInteger& result);
static void montgomery_modular_power_with_minimal_allocations(UnsignedBigInteger const& base, UnsignedBigInteger const& exponent, UnsignedBigInteger const& modulo, UnsignedBigInteger& temp_z0, UnsignedBigInteger& temp_rr, UnsignedBigInteger& temp_one, UnsignedBigInteger& temp_z, UnsignedBigInteger& temp_zz, UnsignedBigInteger& temp_x, UnsignedBigInteger& temp_extra, UnsignedBigInteger& result);

private:
Expand Down
13 changes: 2 additions & 11 deletions Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,8 @@ FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_not_fill_to_one_based_ind
FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
{
UnsignedBigInteger output;
UnsignedBigInteger temp_result;
UnsignedBigInteger temp_plus;

UnsignedBigIntegerAlgorithms::shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
UnsignedBigIntegerAlgorithms::shift_left_without_allocation(*this, num_bits, output);

return output;
}
Expand All @@ -504,11 +502,9 @@ FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_right(size_t num_bits) cons
FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(UnsignedBigInteger const& other) const
{
UnsignedBigInteger result;
UnsignedBigInteger temp_shift_result;
UnsignedBigInteger temp_shift_plus;
UnsignedBigInteger temp_shift;

UnsignedBigIntegerAlgorithms::multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, result);
UnsignedBigIntegerAlgorithms::multiply_without_allocation(*this, other, temp_shift, result);

return result;
}
Expand All @@ -525,11 +521,6 @@ FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(UnsignedBigInteger
return UnsignedDivisionResult { quotient, remainder };
}

UnsignedBigInteger temp_shift_result;
UnsignedBigInteger temp_shift_plus;
UnsignedBigInteger temp_shift;
UnsignedBigInteger temp_minus;

UnsignedBigIntegerAlgorithms::divide_without_allocation(*this, divisor, quotient, remainder);

return UnsignedDivisionResult { quotient, remainder };
Expand Down
Loading
Loading