473,657 Members | 2,593 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting double to float - compiler bug?

Hi,

My program (below) casts a double (which is in range for a float) to a
float. As far as I know this should give me the nearest representable
float, which will loose some precision. I then test for a NAN by comparing
my float to itself (is this correct?), and I get different behaviour with
different compilers. Have I done something that is undefined, or is this a
compiler bug?

Thanks,

Jon.

GCC:

$ ./a.exe
*** NOT A NAN ***
y = 1.5672385692596 4355469

MS Visual C++:

$ ./single
*** NAN ***
y = 1.5672385692596 4360000
#include <stdio.h>

int main(void) {
/* set x to double that is in RANGE for single precision */
double x = 1.5672385729857 ;
/* cast double to float, loosing PRECISION */
float y = (float) x;

/* test for bad y - test for NAN */
if (y != y) {
printf("*** NAN ***\n\n");
printf("y = %10.20f\n", y);
}
else {
printf("*** NOT A NAN ***\n\n");
printf("y = %10.20f\n", y);
}
}


Nov 13 '05 #1
4 13614
In <bg**********@s abina.mathworks .co.uk> "Jonathan Fielder" <jf******@mathw orks.com> writes:
My program (below) casts a double (which is in range for a float) to a
float. As far as I know this should give me the nearest representable
float, which will loose some precision. I then test for a NAN by comparing
my float to itself (is this correct?), and I get different behaviour with
different compilers. Have I done something that is undefined, or is this a
compiler bug?
C89 doesn't specify anything about NANs, but this is not an issue for your
program, which doesn't involve any NANs, your value being in range for
both double and float.
GCC:

$ ./a.exe
*** NOT A NAN ***
y = 1.5672385692596 4355469

MS Visual C++:

$ ./single
*** NAN ***
y = 1.5672385692596 4360000
#include <stdio.h>

int main(void) {
/* set x to double that is in RANGE for single precision */
double x = 1.5672385729857 ;
/* cast double to float, loosing PRECISION */
float y = (float) x;

/* test for bad y - test for NAN */
if (y != y) {
printf("*** NAN ***\n\n");
printf("y = %10.20f\n", y);
}
else {
printf("*** NOT A NAN ***\n\n");
printf("y = %10.20f\n", y);
}
}


I can see no way this program could execute the if branch. If you're
x86-literate, have a look at the assembly code generated by the
compiler. I suspect the compiler has somehow managed to compare the
value before truncation with the value after truncation and found them
different (no surprise!).

You may also want to check the faulty compiler's documentation for an
option disabling certain illegal floating point optimisations that might
be enabled by default (a la gcc's -ffloat-store).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #2
On 6 Aug 2003 16:31:21 GMT, Da*****@cern.ch (Dan Pop) wrote:
In <bg**********@s abina.mathworks .co.uk> "Jonathan Fielder" <jf******@mathw orks.com> writes:
My program (below) casts a double (which is in range for a float) to a
float. As far as I know this should give me the nearest representable
float, which will loose some precision. I then test for a NAN by comparing
my float to itself (is this correct?), and I get different behaviour with
different compilers. Have I done something that is undefined, or is this a
compiler bug?


C89 doesn't specify anything about NANs, but this is not an issue for your
program, which doesn't involve any NANs, your value being in range for
both double and float.
GCC:

$ ./a.exe
*** NOT A NAN ***
y = 1.5672385692596 4355469

MS Visual C++:

$ ./single
*** NAN ***
y = 1.5672385692596 4360000
#include <stdio.h>

int main(void) {
/* set x to double that is in RANGE for single precision */
double x = 1.5672385729857 ;
/* cast double to float, loosing PRECISION */
float y = (float) x;

/* test for bad y - test for NAN */
if (y != y) {
printf("*** NAN ***\n\n");
printf("y = %10.20f\n", y);
}
else {
printf("*** NOT A NAN ***\n\n");
printf("y = %10.20f\n", y);
}
}


I can see no way this program could execute the if branch. If you're
x86-literate, have a look at the assembly code generated by the
compiler. I suspect the compiler has somehow managed to compare the
value before truncation with the value after truncation and found them
different (no surprise!).

You may also want to check the faulty compiler's documentation for an
option disabling certain illegal floating point optimisations that might
be enabled by default (a la gcc's -ffloat-store).

Dan
--


Under MS VC6, if Microsoft extensions are enabled (by default
(/Ze)), the wrong branch is taken. The comparison seems to be
made as you say (I'm too lazy to look at the assembly output -
maybe the OP will want to). Note also that y == x evaluates to
true in this case.

Under MS VC6 If Microsoft extensions are disabled (/Za), the
correct branch is taken.

(To the OP) It is a well-known problem that x86 processors do not
cast from greater precision to lesser precision properly by
default. Floats are 32 bits, doubles are 64 bits, and
intermediate results are stored in 80 bit floating-point
registers. Sometimes values are reloaded from memory at
inappropriate times, such as the case at hand. In essence, y in
an 80-bit floating-point register (maintaining the value of x) is
compared with the 32-bit value of y, and they compare not equal.
If /Za is set, then this behavior is supressed, and the cast is
performed correctly.

Regards,
Bruce Wheeler

Nov 13 '05 #3
Jonathan Fielder wrote:
I then test for a NAN by
comparing my float to itself (is this correct?), and I get different
behaviour with
different compilers.

/* test for bad y - test for NAN */
if (y != y) {
printf("*** NAN ***\n\n");
printf("y = %10.20f\n", y);
}
else {
printf("*** NOT A NAN ***\n\n");
printf("y = %10.20f\n", y);
}
}

Without disagreeing with other respondents, I'd like to point out that gcc
is unusual in not evaluating (y != y) with standard optimizations, at
compile time, by default. If you issue the options -O -ffast-math, it may
choose to evaluate that expression as 0 at compile time. In your case, it
will get the same result with evaluation at run time. The C99 standard,
AFAIK, requires you to use the isnan() function to avoid making this code
depend on compiler options and implementation. Prior to C99, the question
was not addressed, other than by gcc conforming to the informed consensus
of experts.
I would not be surprised if the result you got with your Microsoft compiler
depended on the optimization level.
--
Tim Prince
Nov 13 '05 #4
Thanks!

Jon.

"Jonathan Fielder" <jf******@mathw orks.com> wrote in message
news:bg******** **@sabina.mathw orks.co.uk...
Hi,

My program (below) casts a double (which is in range for a float) to a
float. As far as I know this should give me the nearest representable
float, which will loose some precision. I then test for a NAN by comparing my float to itself (is this correct?), and I get different behaviour with
different compilers. Have I done something that is undefined, or is this a compiler bug?

Thanks,

Jon.

GCC:

$ ./a.exe
*** NOT A NAN ***
y = 1.5672385692596 4355469

MS Visual C++:

$ ./single
*** NAN ***
y = 1.5672385692596 4360000
#include <stdio.h>

int main(void) {
/* set x to double that is in RANGE for single precision */
double x = 1.5672385729857 ;
/* cast double to float, loosing PRECISION */
float y = (float) x;

/* test for bad y - test for NAN */
if (y != y) {
printf("*** NAN ***\n\n");
printf("y = %10.20f\n", y);
}
else {
printf("*** NOT A NAN ***\n\n");
printf("y = %10.20f\n", y);
}
}

Nov 13 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
2160
by: Makhno | last post by:
Hello, Why does my cast from Vector<class Float> to Vector<float> not work? It won't compile, template<class Float> class Vector { public: Vector(Float x1,Float y1,Float z1):x(x1),y(y1),z(z1){} inline Vector<float> operator() () const;
231
23107
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
5
1911
by: el prinCipante | last post by:
I'm getting tired of the following error message. Compiler Error message : Error: Need explicit cast to convert from: float to: float * I am trying to use a routine from the Numerical Recipes library called amebsa.c. The routine requires several parameters of the following form. *iter, **p, *yb.... . How does one initialize these variables? If I declare them as pointer (in this case, *yb and *iter) the compiler still tells me that it...
8
12998
by: Quinn Kirsch | last post by:
Hi all, the following c# example baffles me. my understanding of the managed code of visual .net is that all casts like this would be safe, but this example seems to contradict this notion. if you look at the debugger info, the double dou is half filled w/ garbage bits, instead of those bits being zeroed out appropriately. using System; namespace decimaltodouble {
10
18756
by: Bryan Parkoff | last post by:
The guideline says to use %f in printf() function using the keyword float and double. For example float a = 1.2345; double b = 5.166666667; printf("%.2f\n %f\n", a, b);
5
5272
by: Thorsten | last post by:
Hi everyone, I am rather new to C# and have a problem that will probably seem trivial to most of you... but I hope you can still help me nevertheless.. Via the comport, I read the result of a digital scale... the result is sent as a string like "+0000.23kg", representing the weight in kilograms. In order to work with the returned value, I need to use it as a float or decimal or double... I tried casting it via Convert, via...
23
5280
by: PeterOut | last post by:
If I had code like this. unsigned short usLimit=10 int a, i; for (i=0; i<(int)usLimit; ++i) { a=(int)usLimit; }
17
2214
by: sophia.agnes | last post by:
Hi , I was going through peter van der linden's book Expert C programming, in this book there is a section named "How and why to cast" the author then says as follows (float) 3 - it's a type conversion and the actual bits change. if you say (float) 3.0 it is a type disambiguation,and the compiler can plant the correct bits in the first place.some people say that
32
2373
by: alex.j.k2 | last post by:
Hello all, I have "PRECISION" defined in the preprocessor code and it could be int, float or double, but I do not know in the code what it is. Now if I want to assign zero to a "PRECISION" variable, which of the following lines are correct:
0
8303
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8821
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8502
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7316
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.