-
Notifications
You must be signed in to change notification settings - Fork 18
feat(float): implement arbitrary-precision trigonometric functions and constants #60
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,3 +4,5 @@ | |
| /.vscode/settings.json | ||
| benchmark/Cargo.lock | ||
| benchmark/target | ||
| fuzz/target | ||
| fuzz/Cargo.lock | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -76,6 +76,7 @@ mod fmt; | |
| mod helper_macros; | ||
| mod iter; | ||
| mod log; | ||
| pub mod math; | ||
| mod mul; | ||
| pub mod ops; | ||
| mod parse; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| use crate::{ | ||
| error::assert_limited_precision, | ||
| fbig::FBig, | ||
| repr::{Context, Word}, | ||
| round::{Round, Rounded}, | ||
| }; | ||
| use dashu_base::{BitTest, Sign, UnsignedAbs}; | ||
| use dashu_int::{IBig, UBig}; | ||
|
|
||
| impl<R: Round> Context<R> { | ||
| /// Calculate π using the Chudnovsky algorithm with binary splitting. | ||
| /// | ||
| /// The Chudnovsky algorithm is one of the most efficient methods for | ||
| /// high-precision π calculation, providing ~14.18 decimal digits per term. | ||
| /// | ||
| /// # Methodology | ||
| /// We use Binary Splitting to evaluate the series. This technique transforms | ||
| /// the linear-time summation into a recursive tree evaluation. By combining | ||
| /// terms into large products, it allows the library to leverage fast | ||
| /// multiplication algorithms (like Toom-3 or FFT) as the numbers grow, | ||
| /// leading to significant performance gains over simple iterative summation. | ||
| /// | ||
| /// // TODO: consider adding a static cache for π at common precisions. | ||
| #[must_use] | ||
| pub fn pi<const B: Word>(&self) -> Rounded<FBig<R, B>> { | ||
| assert_limited_precision(self.precision); | ||
|
|
||
| // Calculate required bits based on target precision in base B. | ||
| // bits = ceil(precision * log2(B)) | ||
| let bits = if B.is_power_of_two() { | ||
| self.precision.saturating_mul(B.ilog2() as usize) | ||
| } else { | ||
| self.precision.saturating_mul(B.ilog2() as usize + 1) | ||
| }; | ||
|
|
||
| let num_terms = (bits * 100 / 4708) + 1; | ||
| let guard_bits = num_terms.bit_len() + 32; | ||
| let work_bits = bits + guard_bits; | ||
|
|
||
| // Evaluate the series components using binary splitting | ||
| let (_p, q, t) = chudnovsky_bs(0, num_terms); | ||
|
|
||
| // Final formula: pi = (426880 * sqrt(10005) * Q) / T | ||
|
|
||
| // Convert work bits back to base B precision. | ||
| // precision_B = ceil(work_bits / log2(B)) | ||
| let work_precision = if B == 2 { | ||
| work_bits | ||
| } else { | ||
| work_bits / B.ilog2() as usize + 1 | ||
| }; | ||
| let work_context = Self::new(work_precision); | ||
|
|
||
| let q_f = work_context.convert_int::<B>(q.into()).value(); | ||
| let t_f = work_context.convert_int::<B>(t).value(); | ||
|
|
||
| let sqrt_10005 = work_context | ||
| .sqrt(&work_context.convert_int::<B>(10005.into()).value().repr) | ||
| .value(); | ||
| let constant = work_context.convert_int::<B>(426_880.into()).value(); | ||
|
|
||
| let pi = (constant * sqrt_10005 * q_f) / t_f; | ||
| pi.with_precision(self.precision) | ||
| } | ||
| } | ||
|
|
||
| /// Binary splitting implementation for the Chudnovsky series. | ||
| /// Returns (P, Q, T) for the range [a, b). | ||
| fn chudnovsky_bs(a: usize, b: usize) -> (UBig, UBig, IBig) { | ||
| if b - a == 1 { | ||
| // Base case: calculate single term | ||
| if a == 0 { | ||
| return (UBig::ONE, UBig::ONE, IBig::from_parts_const(Sign::Positive, 13_591_409)); | ||
| } | ||
|
|
||
| let k = a as u64; | ||
| let p = UBig::from(6 * k - 5) * (2 * k - 1) * (6 * k - 1); | ||
| let q = UBig::from(k).pow(3) * UBig::from(10_939_058_860_032_000_u64); | ||
| let t_val = IBig::from_parts_const(Sign::Positive, 13_591_409) | ||
| + IBig::from_parts_const(Sign::Positive, 545_140_134) * k; | ||
| let t_abs = &p * t_val.unsigned_abs(); | ||
| let t = IBig::from(t_abs) * Sign::from(a % 2 == 1); | ||
| return (p, q, t); | ||
| } | ||
|
|
||
| // Recursive step | ||
| let mid = (a + b) / 2; | ||
| let (p_l, q_l, t_l) = chudnovsky_bs(a, mid); | ||
| let (p_r, q_r, t_r) = chudnovsky_bs(mid, b); | ||
|
|
||
| let p = &p_l * &p_r; | ||
| let q = &q_l * &q_r; | ||
| // T = T_L * Q_R + T_R * P_L | ||
| let t = IBig::from(q_r) * t_l + IBig::from(p_l) * t_r; | ||
| (p, q, t) | ||
| } | ||
|
|
||
| impl<R: Round, const B: Word> FBig<R, B> { | ||
| /// Calculate π with the given precision and the default rounding mode. | ||
| #[inline] | ||
| #[must_use] | ||
| pub fn pi(precision: usize) -> Self { | ||
| Context::<R>::new(precision).pi().value() | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,31 +1,86 @@ | ||
| //! Implementations of advanced math functions | ||
| //! Advanced mathematical functions | ||
|
|
||
| // TODO: implement the math functions as associated methods, and add them to FBig through a trait | ||
| // REF: https://pkg.go.dev/github.com/ericlagergren/decimal | ||
| use crate::{ | ||
| error::{panic_infinite, panic_nan, panic_overflow, panic_underflow}, | ||
| fbig::FBig, | ||
| repr::{Context, Repr, Word}, | ||
| round::{Round, Rounded}, | ||
| }; | ||
|
|
||
| enum FpResult { | ||
| Normal(Repr), | ||
| pub mod consts; | ||
| pub mod trig; | ||
|
|
||
| /// The result of an advanced mathematical operation. | ||
| /// | ||
| /// This enum is used to handle non-finite results (NaN, Infinite) and | ||
| /// boundary conditions (Overflow, Underflow) without panicking, | ||
| /// as the core [`FBig`] type only represents finite numbers. | ||
| /// | ||
| /// Finite results are wrapped in a [Rounded] to preserve rounding information. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| pub enum FpResult<const B: Word> { | ||
| Normal(Rounded<Repr<B>>), | ||
| Overflow, | ||
| Underflow, | ||
| NaN, | ||
|
|
||
| /// An exact infinite result is obtained from finite inputs, such as | ||
| /// divide by zero, logarithm on zero. | ||
| /// divide by zero or logarithm of zero. | ||
| Infinite, | ||
| } | ||
|
|
||
| impl Context { | ||
| fn sin(&self, repr: Repr) -> FpResult { | ||
| todo!() | ||
| impl<const B: Word> FpResult<B> { | ||
| /// Convert the result into an [`FBig`] with the given context. | ||
| /// | ||
| /// # Panics | ||
| /// Panics if the result is not `Normal`. | ||
| #[inline] | ||
| #[must_use] | ||
| pub fn value<R: Round>(self, context: &Context<R>) -> FBig<R, B> { | ||
| match self { | ||
| Self::Normal(rounded) => FBig::new(rounded.value(), *context), | ||
| Self::NaN => panic_nan(), | ||
| Self::Infinite => panic_infinite(), | ||
| Self::Overflow => panic_overflow(), | ||
| Self::Underflow => panic_underflow(), | ||
| } | ||
| } | ||
|
|
||
| /// Convert the result into an optional [`FBig`] with the given context. | ||
| /// Returns `None` if the result is not `Normal`. | ||
| #[inline] | ||
| #[must_use] | ||
| pub fn ok<R: Round>(self, context: &Context<R>) -> Option<Rounded<FBig<R, B>>> { | ||
| match self { | ||
| Self::Normal(rounded) => Some(rounded.map(|repr| FBig::new(repr, *context))), | ||
| _ => None, | ||
| } | ||
| } | ||
|
|
||
| /// Returns `true` if the result is `NaN`. | ||
| #[inline] | ||
| #[must_use] | ||
| pub const fn is_nan(&self) -> bool { | ||
| matches!(self, Self::NaN) | ||
| } | ||
|
|
||
| /// Returns `true` if the result is `Infinite`. | ||
| #[inline] | ||
| #[must_use] | ||
| pub const fn is_infinite(&self) -> bool { | ||
| matches!(self, Self::Infinite) | ||
| } | ||
| } | ||
|
|
||
| trait ContextOps { | ||
| fn context(&self) -> &Context; | ||
| fn repr(&self) -> &Repr; | ||
| /// Returns `true` if the result is a normal finite value. | ||
| #[inline] | ||
| #[must_use] | ||
| pub const fn is_normal(&self) -> bool { | ||
| matches!(self, Self::Normal(_)) | ||
| } | ||
|
|
||
| /// Returns `true` if the result is a finite value (Normal, Overflow, or Underflow). | ||
| #[inline] | ||
| fn sin(&self) -> FpResult { | ||
| self.context().sin(self.repr()) | ||
| #[must_use] | ||
| pub const fn is_finite(&self) -> bool { | ||
| matches!(self, Self::Normal(_) | Self::Overflow | Self::Underflow) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.