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

Alias macro #6

Merged
merged 3 commits into from
Mar 8, 2024
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
10 changes: 10 additions & 0 deletions src/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ pub trait RoundingContext {
fn round<T: Real>(&self, val: &T) -> Self::Format;
}

/// Similar to the unstable `trait_alias` feature,
/// associates a groups a set of traits into a single named trait.
#[macro_export]
macro_rules! context_alias {
($id:ident, $t0:ident $(+ $ti:ident )* ) => {
trait $id: RoundingContext + $t0 $(+ $ti )* {}
impl<T : RoundingContext + $t0 $(+ $ti )*> $id for T {}
};
}

/// Rounding modes for rounding contexts.
///
/// The following enumeration encodes a list of rounding modes to handle
Expand Down
34 changes: 16 additions & 18 deletions tests/quadratic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,27 @@ use mpmfnum::ieee754::IEEE754Context;
use mpmfnum::ops::*;
use mpmfnum::*;

trait QuadraticCtx:
RoundingContext + RoundedNeg + RoundedAdd + RoundedSub + RoundedMul + RoundedDiv + RoundedSqrt
{
}

impl<T> QuadraticCtx for T where
T: RoundingContext
+ RoundedNeg
+ RoundedAdd
+ RoundedSub
+ RoundedMul
+ RoundedDiv
+ RoundedSqrt
{
}
context_alias!(
QuadraticCtx,
RoundedNeg + RoundedAdd + RoundedSub + RoundedMul + RoundedDiv + RoundedSqrt
);

fn naive_quadp<Ctx>(a: &Ctx::Format, b: &Ctx::Format, c: &Ctx::Format, ctx: &Ctx) -> Ctx::Format
fn naive_quad<Ctx>(
a: &Ctx::Format,
b: &Ctx::Format,
c: &Ctx::Format,
ctx: &Ctx,
) -> (Ctx::Format, Ctx::Format)
where
Ctx: QuadraticCtx,
{
let two = RFloat::Real(false, 1, Integer::one());
let four = RFloat::Real(false, 2, Integer::one());
let discr = ctx.sqrt(&ctx.sub(&ctx.mul(b, b), &ctx.mul(&four, &ctx.mul(a, c))));
ctx.div(&ctx.add(&ctx.neg(b), &discr), &ctx.mul(&two, a))
let pos = ctx.add(&ctx.neg(b), &discr);
let neg = ctx.sub(&ctx.neg(b), &discr);
let factor = ctx.mul(&two, a);
(ctx.div(&pos, &factor), ctx.div(&neg, &factor))
}

#[test]
Expand All @@ -38,5 +35,6 @@ fn run() {
let b = ctx.zero(false);
let c = ctx.zero(false);

let r = naive_quadp(&a, &b, &c, &ctx);
let (pos, neg) = naive_quad(&a, &b, &c, &ctx);
println!("{:?} {:?}", pos, neg);
}
Loading