This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Cast difference between GCC on Linux and Forte on Solaris
- From: Charles Lawson <clawson301 at earthlink dot net>
- To: gcc-help at gcc dot gnu dot org
- Date: Mon, 15 Jul 2002 08:15:06 -0700
- Subject: Re: Cast difference between GCC on Linux and Forte on Solaris
Regarding the computational statement:
ires1 = (int) (log(64.0)/log(2.0)) ;
Returning 5 in one computer system and 6 in another.
The function "log" in C (and in Fortran) computes a machine
approximation go the "natural" logarithm, i.e., the logarithm to the
base "e", where e = 2.71828... .
The expected results would be log(64) = 4.15888... and log(2) =
.693147...
Using the 6-decimal digit approximations shown here, dividing the first
by the second gives 5.9999971... .
Since the values of log(64) and log(2) cannot be represented exactly in
a finite number of digits (in either decimal notation or in base 2, used
in your computer) you can only expect the results to be approximate.
Theoretically it is clear that log(64)/log(2) is exactly 6, but
computing this by division using two approximate values can only be
expected to return a value close to 6. If it returns 6 or a value
slightly larger, the "int" function will return 6, whereas if the
computed quotient is slightly smaller than 6, the "int" function will
return 5.
Your line of C code, as it stands, must be regarded as simply a way to
return either 5 or 6, randomly on different computer systems. If you
need a consistent result on different computer systems, then you must go
back a bit in your algorithm design. A suitable design must take into
account more carefully where the source data is coming from and what is
the desired use of the computed results.
Keep in mind two facts of mathematics and computing: (1) The "int"
function is a discontinuous mathematical function, in fact it can be
called a "step" function. As the argument makes a small change from
being just below an integer value to just above an integer value, the
value of "int" makes a relatively large change from one integer value to
the next. (2) Computation with floating point numbers and evaluation of
transendental mathematical functions, such as "log" are only approximate
on a computer. One cannot expect various mathematical identities, such
as "log(64)/log(2) = 6" to hold in floating point arithmetic.
Best regards, Chuck Lawson