[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: initialization of float arrays
From: |
Jens Hannemann |
Subject: |
Re: initialization of float arrays |
Date: |
Fri, 7 Sep 2001 09:20:21 +0200 |
User-agent: |
KNode/0.4 |
Gabriel Zachmann wrote:
> When I have an array like this:
>
> float qs[][4] = { {-0.441726, -0.441726, 0.552158, -0.552158} ,
> {res/2, res/2, res/2, res/2 },
> {res/2-1, res/2-1, res/2-1, res/2 },
> {res/2, -res/2+0.1, -res/2+0.1, -res/2+0.1 },
> };
>
> I see in gdb this:
>
> (gdb) p qs
> $12 = {{-0.441725999, -0.441725999, 0.552157998, -0.552157998}, {1,
> 1, 1}, {
> 0, 0, 0, 1}, {1, 2.14748365e+09, 2.14748365e+09, 2.14748365e+09}}
> (gdb) p res
> $13 = 2
>
> which is, of course, bogus.
Which is probably not bogus, since most likely res is of type unsigned
int. If I compile the following program on my UltraSparc using g++ 3.0:
#include <iostream>
int main()
{
unsigned int res=2;
std::cout << -res/2+0.1 << std::endl;
std::cout << 0.1-res/2 << std::endl;
res=1;
std::cout << -res/2+0.1 << std::endl;
std::cout << 0.1-res/2 << std::endl;
std::cout << 0.1-res/2.0 << std::endl;
return 0;
}
the output is
2.14748e+09
-0.9
2.14748e+09
0.1
-0.4
The point here is that you cannot negate an unsigned int without nasty
effects. Negation will result in taking the variable's twos complement,
and since the variable is declares unsigned, the resulting bit pattern
will be interpreted as a positive number again. I suggest an explicit
cast to float (-static_cast<float>(res)/2+0.1) or reordering the
expression to utilize automatic type conversion (0.1-res/2). But
beware, with writing res/2 you request integer division, so if res
equals 1, res/2 will yield zero. To be really safe, you should request
float division by using a floating point literal (0.1-res/2.0).
Please read about automatic type conversion and promotion in the C or
C++ book of your choice to avoid future pitfalls.
Best regards,
Jens
--
Dipl.-Ing. Jens Hannemann address@hidden
Computational Electromagnetics Group, University at Kiel, Germany
Homepage: http://www.cem.tf.uni-kiel.de/~jh/ -- PGP key available