Skip to content

Commit

Permalink
macro
Browse files Browse the repository at this point in the history
  • Loading branch information
bksaiki committed Mar 8, 2024
1 parent 1ccae08 commit a956fea
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 18 deletions.
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
26 changes: 8 additions & 18 deletions tests/quadratic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,19 @@ 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 +27,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);
}

0 comments on commit a956fea

Please sign in to comment.