From a956feae11cb7f7beb28621b13f15afdea01d195 Mon Sep 17 00:00:00 2001 From: Brett Saiki Date: Thu, 7 Mar 2024 20:21:51 -0800 Subject: [PATCH] macro --- src/round.rs | 10 ++++++++++ tests/quadratic.rs | 26 ++++++++------------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/round.rs b/src/round.rs index a6158c9..43dfcd3 100644 --- a/src/round.rs +++ b/src/round.rs @@ -24,6 +24,16 @@ pub trait RoundingContext { fn round(&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 $id for T {} + }; +} + /// Rounding modes for rounding contexts. /// /// The following enumeration encodes a list of rounding modes to handle diff --git a/tests/quadratic.rs b/tests/quadratic.rs index c90a38a..0ff78e1 100644 --- a/tests/quadratic.rs +++ b/tests/quadratic.rs @@ -5,30 +5,19 @@ use mpmfnum::ieee754::IEEE754Context; use mpmfnum::ops::*; use mpmfnum::*; -trait QuadraticCtx: - RoundingContext + RoundedNeg + RoundedAdd + RoundedSub + RoundedMul + RoundedDiv + RoundedSqrt -{ -} - -impl QuadraticCtx for T where - T: RoundingContext - + RoundedNeg - + RoundedAdd - + RoundedSub - + RoundedMul - + RoundedDiv - + RoundedSqrt -{ -} +context_alias!(QuadraticCtx, RoundedNeg, RoundedAdd, RoundedSub, RoundedMul, RoundedDiv, RoundedSqrt); -fn naive_quadp(a: &Ctx::Format, b: &Ctx::Format, c: &Ctx::Format, ctx: &Ctx) -> Ctx::Format +fn naive_quad(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] @@ -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); }