comp.lang.ada
 help / color / mirror / Atom feed
From: Robert A Duff <bobduff@shell01.TheWorld.com>
Subject: Re: evaluation of named numbers
Date: Sun, 17 Oct 2010 12:05:03 -0400
Date: 2010-10-17T12:05:03-04:00	[thread overview]
Message-ID: <wcc39s4pzyo.fsf@shell01.TheWorld.com> (raw)
In-Reply-To: 2304722c-027d-42f6-a45d-5a7646c35cf6@t8g2000yqk.googlegroups.com

Rolf <rolf.ebert_nospam_@gmx.net> writes:

> I always thought that named numbers are fully evaluated with (almost)
> unlimited precision at compile time.

Static expressions are always evaluated exactly.  There's no "almost"
about it -- if the compiler runs out of memory trying, then it should
print an error message rather than producing an inexact result.

Named numbers are always static, so that applies to them.

>... I was quite astonished to see
>
>   Ticks : constant := 20 / 1000 * 16_000_000 / 8; -- 40_000 ticks

However, the "/" operator on integer types throws away the remainder
(whether static or at run time).  That's the "/" operator for
root_integer in this case.  20/1000 is exactly 0 in Ada, and that's what
the compiler is calculating.  That's "wrong" in the maths sense, where
20/1000 is "one fiftieth" or "zero with a remainder of 20", or various
other definitions, but never "exactly 0".

If you write it like this:

Ticks : constant := 20.0 / 1000.0 * 16_000_000.0 / 8.0;

then it will use the "/" for root_real, which will
calculate a mathematically correct answer.

It's annoying that Ada (and lots of other languages) use
a mathematically wrong definition of division, but that's
the way it is.  It's also annoying that the type of
a literal is determined by the mere presence or absence
of ".0".

By the way, if you write "-- 40_000 ticks" like this:

    pragma Assert(Ticks = 40_000);

you will be notified if it's wrong.  ;-)

> evaluated to 0 and not to the expected 40.000. It seems that the
> compiler uses integer numbers also for intermediate results and 20 /
> 1000 ends up to be 0 instead of 0.02. Any decent pocket calculator
> gets that right.

I'm no expert in pocket calculators, but I think most of them
use floating point (possibly decimal floating point?),
so they do not always calculate exactly-correct results
with arbitrary precision.  And they tend to have less
memory than is available to an Ada compiler.  ;-)

- Bob



  parent reply	other threads:[~2010-10-17 16:05 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2010-10-17 15:01 evaluation of named numbers Rolf
2010-10-17 15:28 ` Vinzent Hoefler
2010-10-17 16:05 ` Robert A Duff [this message]
2010-10-17 18:32   ` Georg Bauhaus
2010-10-17 18:57 ` Nasser M. Abbasi
2010-10-17 22:30 ` anon
2010-10-17 22:32 ` anon
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox