473,809 Members | 2,575 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

float variables in loops

Hello,

What happens to float variable in loops. For example,

float f=8.7;
if(f<8.7)
printf("less");
else if(f==8.7)
printf("equal") ;
else if(f>8.7)
printf("more");

prints "less". Shouldn't it print "equal".

regards,
vijay.

Nov 14 '05 #1
8 3474
In article <11************ *********@o13g2 000cwo.googlegr oups.com>,
"vijay" <Ta***********@ yahoo.com> wrote:
Hello,

What happens to float variable in loops. For example,

float f=8.7;
if(f<8.7)
printf("less");
else if(f==8.7)
printf("equal") ;
else if(f>8.7)
printf("more");

prints "less". Shouldn't it print "equal".


No, it shouldn't.

What is the type of f?
What is the type of 8.7?
Are they the same types?
Nov 14 '05 #2
vijay <Ta***********@ yahoo.com> wrote:
What happens to float variable in loops. For example, float f=8.7;
if(f<8.7)
printf("less");
else if(f==8.7)
printf("equal") ;
else if(f>8.7)
printf("more"); prints "less". Shouldn't it print "equal".


No, you can't expect that. The basic problem is that numbers are
stored with a finite number of digits. And numbers like 8.7 are
no simple looking numbers anymore when converted to binary but
have an infinite number of digits (like one third is an infinite
fraction when written in base 10). But since you only have a
finite numbers of bits to store them in, the numbers get truncated.
So most floating point numbers can be stored only as an approxi-
mation and what's stored of your 8.7 is probably something like
8.6999998 instead of 8.7 - you can easily see that effect when
you try to print it out with enough digits, try e.g.

printf( "%20.18f\n" , f );

Moreover, since (usually) floats have less bits than doubles,
the same number stored in a float and a double variable will
differ - just try it out with

printf( "%20.18f %20.18f\n", f, 8.7 );

This also indicates that "8.7" isn't treated as a float but
as a double - all calculations in C are done per default in
double and all constants like "8.7" are treated as doubles -
to avoid that you would have to write "8.7f" instead. So what
you do in your program is comparing the value of the float
variable 'f' with the value of 8.7 when stored as a double.
But since these values typically differ you hardly ever will
get "less" printed out (except for numbers that can be stored
using a small number of digits, your result would be different
if you would use e.g. 2.5 instead of 8.7).

So the first thing to keep in mind when dealing with floating
point numbers is that comparing them for equaliy will typically
only work by accident.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #3
vijay wrote:
Hello,

What happens to float variable in loops. For example,

float f=8.7;
if(f<8.7)
printf("less");
else if(f==8.7)
printf("equal") ;
else if(f>8.7)
printf("more");

prints "less". Shouldn't it print "equal".

regards,
vijay.


FAQs already address this issue.

Please read followings ..

http://www.eskimo.com/~scs/C-faq/q14.4.html
http://www.eskimo.com/~scs/C-faq/q14.5.html
Krishanu
Nov 14 '05 #4

Jens.Toerr...@p hysik.fu-berlin.de wrote:
vijay <Ta***********@ yahoo.com> wrote:
What happens to float variable in loops. For example,

float f=8.7;
if(f<8.7)
printf("less");
else if(f==8.7)
printf("equal") ;
else if(f>8.7)
printf("more");

prints "less". Shouldn't it print "equal".


No, you can't expect that. The basic problem is that numbers are
stored with a finite number of digits. And numbers like 8.7 are
no simple looking numbers anymore when converted to binary but
have an infinite number of digits (like one third is an infinite
fraction when written in base 10). But since you only have a
finite numbers of bits to store them in, the numbers get truncated.
So most floating point numbers can be stored only as an approxi-
mation and what's stored of your 8.7 is probably something like
8.6999998 instead of 8.7 - you can easily see that effect when
you try to print it out with enough digits, try e.g.

printf( "%20.18f\n" , f );

Moreover, since (usually) floats have less bits than doubles,
the same number stored in a float and a double variable will
differ - just try it out with

printf( "%20.18f %20.18f\n", f, 8.7 );


8.6999998092651 36719
8.6999999999999 99289

This is the output I get. How is it really calculated? Does the output
depend upon the compiler(i'm using gcc), system etc.

printf( "%20.18f %20.18f\n", f, 8.7f );
gives the same output, maybe because now it treats 8.7 as a float and
not as a double.

regards,
vijay.

Nov 14 '05 #5

"vijay" <Ta***********@ yahoo.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .


printf( "%20.18f %20.18f\n", f, 8.7 );


8.6999998092651 36719
8.6999999999999 99289

This is the output I get. How is it really calculated? Does the output
depend upon the compiler(i'm using gcc), system etc.

If your system uses open source libraries, such as glibc or newlib, you have
the opportunity to look up how printf() et al. do their work. Or, look up
ideas in a fine reference, such as Plauger's "Standard C Library." On many
systems, where there is a choice of gcc or other compilers, the same
printf() would be shared by multiple compilers. A library will comply with
IEEE standard if it gets 17 digits right, for the standard 64-bit double.
Accuracy of additional digits may depend on whether your system supports
long double.
Nov 14 '05 #6
On Wed, 04 May 2005 08:11:51 +0000, Jens.Toerring wrote:

....
printf( "%20.18f %20.18f\n", f, 8.7 );

This also indicates that "8.7" isn't treated as a float but
as a double - all calculations in C are done per default in
double


That was true for K&R C but is not true in standard C where operations
involving operands of type float or float in combination with
integer operands produce a float result.

The default argument promotions, where (amongst other things) a float
argument gets promoted to double in an unprototyped function call or in a
variable argument list, still exist in standard C but don't affect
"calculatio ns".

Lawrence

Nov 14 '05 #7
On 4 May 2005 06:24:23 -0700, vijay
<Ta***********@ yahoo.com> wrote:
Jens.Toerr...@p hysik.fu-berlin.de wrote:

No, you can't expect that. The basic problem is that numbers are
stored with a finite number of digits. And numbers like 8.7 are
no simple looking numbers anymore when converted to binary but
have an infinite number of digits (like one third is an infinite
fraction when written in base 10). But since you only have a
finite numbers of bits to store them in, the numbers get truncated.
So most floating point numbers can be stored only as an approxi-
mation and what's stored of your 8.7 is probably something like
8.6999998 instead of 8.7 - you can easily see that effect when
you try to print it out with enough digits, try e.g.

printf( "%20.18f\n" , f );

Moreover, since (usually) floats have less bits than doubles,
the same number stored in a float and a double variable will
differ - just try it out with

printf( "%20.18f %20.18f\n", f, 8.7 );
8.6999998092651 36719
8.6999999999999 99289

This is the output I get. How is it really calculated? Does the output
depend upon the compiler(i'm using gcc), system etc.


It depends on the respresentation of float and double on your system,
which will be related to the compiler and the hardware. The standard
says only that a float must have at least 6 digits of precision and a
double at least 10 digits, but they could be identical on some systems
as long as they meet the minimum criteria.
printf( "%20.18f %20.18f\n", f, 8.7f );
gives the same output, maybe because now it treats 8.7 as a float and
not as a double.


I assume you mean that both outputs are the same. Yes, if you just say
8.7 it is interpreted as a double (6.4.4.1 para 4), if you say 8.7f then
it will be a float.

In general, however, comparing floating point numbers for exact equality
is not sensible, because rounding can occur without you knowing it. For
instance, 9.7 - 8.7 == 1.0 may well fail, as may (x+1) - 1 == x. In
general the way to test is for "near equality", choose some value
EPSILON and do something like:

if (abs(expression ) < EPSILON)
/* near enough */

or even write it as a function so that it auto-scales epsilon according
to numbers being compared:

#include <float.h>
#include <math.h>

int float_compare(f loat a, float b)
{
float epsilon = (fabs(a) + fabs(b)) * FLT_EPSILON;
if (a - b > epsilon) return +1;
if (b - a > epsilon) return -1;
return 0;
}

Chris C
Nov 14 '05 #8
In message <pa************ *************** *@netactive.co. uk>
Lawrence Kirby <lk****@netacti ve.co.uk> wrote:
On Wed, 04 May 2005 08:11:51 +0000, Jens.Toerring wrote:

...
printf( "%20.18f %20.18f\n", f, 8.7 );

This also indicates that "8.7" isn't treated as a float but
as a double - all calculations in C are done per default in
double


That was true for K&R C but is not true in standard C where operations
involving operands of type float or float in combination with
integer operands produce a float result.


That's a half-truth. Yes, the result has semantic type float, but it's
allowed to have extra precision. Thus in:

float f;
double d = f * f;

the final result d may have full double precision, or it may just have
float precision, depending on FLT_EVAL_METHOD . So the traditional
mode of operation where "all calculations in C are done per default in
double" is still an implementation option.

And, even more bizarrely - something I didn't know until recently - even
constants might have more precision than their type. So

double d = 8.7F;

could leave you with full double precision. Bleurgh. The only way to
guarantee a single-precision constant is:

float f = 8.7F;
or
double d = (float) 8.7F;

--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
182-190 Newmarket Road Fax: +44 (0) 1728 727430
Cambridge, CB5 8HE, United Kingdom WWW: http://www.tematic.com/
Nov 14 '05 #9

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

Similar topics

3
2055
by: sarmin kho | last post by:
Hi Pythoners, i have been using a lot of global variables in the python script i am working on. the global variables are shared and used by all various 'definitions' : def name (): global all globs... ..... my question is: 'is it safe using global variables in term of its execution time?
0
406
by: andrea_gavana | last post by:
Hello NG, probably because I still have Python 2.3.4, these are the results I'm getting: C:\Python23\Lib>python timeit.py -s "floats = map(float, range(1000))" "ints = m ap(int, floats)" 1000 loops, best of 3: 398 usec per loop
13
2727
by: Michele Guidolin | last post by:
Hello to everybody. I'm doing some benchmark about a red black Gauss Seidel algorithm with 2 dimensional grid of different size and type, I have some strange result when I change the computation from double to float. Here are the time of test with different grid SIZE and type: SIZE 128 256 512
9
2493
by: Javaman59 | last post by:
Using local declarations within a block often makes code more readable, but is it less efficient? eg... void P() { while (...) { int i = ...; bool b = ...; .... } }
15
2991
by: k3n3dy | last post by:
Hello everybody, I would like to ask anybody to help me understand what should be done exactly with this Problem. I have provided what I have up to now, although it is not quite accurate. Create a class to operate on the US currency. Call the new class Money. All the data components in this class for dollars and cents are integer variables (this is where I get confused and don't know how to actually do the job). Include member functions...
16
11288
by: chandanlinster | last post by:
As far as I know floating point variables, that are declared as float follow IEEE format representation (which is 32-bit in size). But chapter1-page no 9 of the book "The C programming language" states that "THE RANGE OF BOTH int AND float DEPENDS ON THE MACHINE YOU ARE USING". Does this mean "float" variables have different sizes on different machines?
10
3916
by: Chris Stankevitz | last post by:
Is this a fast way to invert a float: inline Invert(float& f) { f *= -1.0f; } I'd like the CPU to flip the sign bit (and not carry out a float-float multiplication). Please enlighten me! I'm going be performing a lot of these.
13
6196
by: Shirsoft | last post by:
I have a 32 bit intel and 64 bit AMD machine. There is a rounding error in the 8th digit. Unfortunately because of the algorithm we use, the errors percolate into higher digits. C++ code is ------------------ b += (float)(mode *val); On 32 bit(intel , vs 2003, C++), some watch variables are
6
2988
by: =?Utf-8?B?QUw=?= | last post by:
Hi I usually stick to the convention of not declaring variables in my bodies of "loops" (including foreach) ie int x; for (int i = 0; i < 10; i++) {
0
9603
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,...
1
10387
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
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
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...
0
6881
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();...
0
5689
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
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.