From: Niklas Holsti <niklas.holsti@tidorum.invalid>
Subject: Re: Saturation arithmetic woes.
Date: Wed, 29 Jul 2009 22:14:44 +0300
Date: 2009-07-29T22:14:44+03:00 [thread overview]
Message-ID: <4a709faf$0$6282$4f793bc4@news.tdc.fi> (raw)
In-Reply-To: <1a16b458-0201-4320-9787-2836ed58f991@e27g2000yqm.googlegroups.com>
In addition to the replies from Martin and Dmitry regarding the absence
of a "+" operator for Discrete_Type, I would like to comment on the
logic of your saturated-"+":
xorque wrote:
> package body Saturation is
>
> function "+"
> (Left : Saturated_Type;
> Right : Saturated_Type) return Saturated_Type
> is
> Temp_Left : constant Discrete_Type := Discrete_Type (Left);
> Temp_Right : constant Discrete_Type := Discrete_Type (Right);
> begin
> if Temp_Left + Temp_Right > Discrete_Type'Last then
Depending on the actual type associated with Discrete_Type (and assuming
you use the predefined "+" for that type), you risk getting an overflow
on Temp_Left + Temp_Right. If you have overflow checks disabled (as Gnat
has by default) the sum may "wrap around" and seem to be less than
Discrete_Type'Last, giving you the wrong result. If you have overflow
checks enabled, you get a Constraint_Error instead of
Discrete_Type'Last. Ditto for underflow and Discrete_Type'First.
One option is to have two formal types, one that defines the range for
saturation (as Discrete_Type in your code) and another that is wide
enough to compute the sum of Left and Right without under- or overflow.
If the other type is called Wide_Type, you could then replace Temp_Left
and Temp_Right with
Sum : constant Wide_Type := Wide_Type (Left) + Wide_Type (Right);
which would simplify your code a bit. Or just write one expression:
return Discrete_Type (
Wide_Type'Min (Wide_Type (Discrete_Type'Last),
Wide_Type'Max (Wide_Type (Discrete_Type'First),
Wide_Type (Left) + Wide_Type (Right))));
That assumes that the formal Wide_Type is defined as an integer type,
not just as any discrete type.
HTH,
--
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
. @ .
next prev parent reply other threads:[~2009-07-29 19:14 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2009-07-29 17:03 Saturation arithmetic woes xorque
2009-07-29 17:13 ` Martin
2009-07-29 18:14 ` Jeffrey R. Carter
2009-07-29 19:14 ` Niklas Holsti [this message]
2009-07-29 19:39 ` xorque
2009-07-30 9:09 ` Jean-Pierre Rosen
2009-07-30 11:51 ` Martin
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox