473,320 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

++ / -- operators with floats and doubles

Yesterday I found in a piece of code a float being incremented with ++.
For some reason (wrong, I guess...) I thought that only integer types
could be incremented that way, and I had never seen floats or doubles
incremented that way before. Just to be sure I did a toy program and
compiled with gcc -ansi -pedantic -Wall and it worked without any error
or warning, showing the correct result.
Is it correct to increment floats or doubles with ++ and --? Is it
defined or am I getting into the realm of undefined behaviour? If it's
correct, can you think of a place where it could be useful?
Many thanks for your time,
Al

Nov 14 '05 #1
14 1655
my**************@gmail.com wrote:
Is it correct to increment floats or doubles with ++ and --? Is it
defined or am I getting into the realm of undefined behaviour?
Any scalar type may be incremented.
You can also increment pointers.
If it's
correct, can you think of a place where it could be useful?


Any time that you might want to increase the value of a float by one.
It could happen, right?

--
pete
Nov 14 '05 #2
> Any time that you might want to increase the value of a float by one.
It could happen, right?


I think the problem with floats is that, depending on the magnitude of
the float, it may be a noop.

Jon
----
Learn to program using Linux assembly language
http://www.cafeshops.com/bartlettpublish.8640017
Nov 14 '05 #3

"Jonathan Bartlett" <jo*****@eskimo.com> wrote
Any time that you might want to increase the value of a float by one.
It could happen, right?


I think the problem with floats is that, depending on the magnitude of the
float, it may be a noop.

The other problem is that adding one isn't the same as incrementing.
Incrementing is what you do when you count, adding one is adding a constant
that happens to be unity.
So if I am counting spectators as they pass throught he turnstiles to a
football match, it makes sense to say
count++
every time someone passes through.
On the other hand current rules are that a win is three points, whilst a
draw is one point, and a loss no points. It is not right to say
if(goalsfor == goalsagainst)
points++;
It should be
points += 1;
To make clear that 1 is an externally-defined constant that could change.
The rules could change so that a draw scores zero whilst a loss is minus
one, for example.

Floating point values aren't generally used for counting, that's what we
have integers for. So it doesn't usually make sense to increment them.
Nov 14 '05 #4
Jonathan Bartlett wrote:
Any time that you might want to increase the value of a float by
one. It could happen, right?


I think the problem with floats is that, depending on the magnitude
of the float, it may be a noop.


float a, b;

a = 0.0;
do {
b = a++;
} while (a != b);
printf("%f\n", a);

and time its execution. It will terminate on any machine known to
me. Then change 'float' to 'double' and try again.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #5
Malcolm wrote:
The other problem is that adding one isn't the same as incrementing.
In C, it is.
Floating point values aren't generally used for counting,
that's what we have integers for.
So it doesn't usually make sense to increment them.


I agree.

--
pete
Nov 14 '05 #6
In message <42***********@mindspring.com>
pete <pf*****@mindspring.com> wrote:
my**************@gmail.com wrote:
Is it correct to increment floats or doubles with ++ and --? Is it
defined or am I getting into the realm of undefined behaviour?


Any scalar type may be incremented.


Except complex and imaginary types.

--
Kevin Bracey, Principal Software Engineer
Tematic Ltd Tel: +44 (0) 1223 503464
3 Signet Court, Swann Road, Fax: +44 (0) 1728 727430
Cambridge, CB5 8LA, United Kingdom WWW: http://www.tematic.com/
Nov 14 '05 #7
Jonathan Bartlett wrote:
Any time that you might want to increase the value of a float by one.
It could happen, right?
I think the problem with floats is that,
depending on the magnitude of the float, it may be a noop.


You think?
cat main.c #include <stdio.h>

int main(int argc, char* argv[]) {
float x = 0.0, y;
do {
y = x;
++x;
} while (y < x);
fprintf(stdout, "x = %f\n", x);
//do {
// y = x;
// } while (y < ++x);
//fprintf(stdout, "x = %f\n", x);
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main

x = 16777216.000000
Nov 14 '05 #8
E. Robert Tisdale wrote:
Jonathan Bartlett wrote:
Any time that you might want to increase the value of a float by one.
It could happen, right?

I think the problem with floats is that, depending on the magnitude of
the float, it may be a noop.

You think?
> cat main.c

#include <stdio.h>

int main(int argc, char* argv[]) {
float x = 0.0, y;
do {
y = x;
++x;
} while (y < x);
fprintf(stdout, "x = %f\n", x);
//do {
// y = x;
// } while (y < ++x);
//fprintf(stdout, "x = %f\n", x);
return 0;
}
> gcc -Wall -std=c99 -pedantic -o main main.c
> ./main

x = 16777216.000000


If I change the example above to

int main(void)
{
float x = 0.0;

while (x < x + 1) { x++; }
fprintf(stdout, "x = %f\n", x);
return 0;
}

the program doesn't seem to terminate. To me they seem to be more or
less equivalent. Why does it behave differently?

-- August
Nov 14 '05 #9
August Karlstrom wrote:
If I change the example above to

int main(void) {
float x = 0.0;

while (x < x + 1) { x++; }
fprintf(stdout, "x = %f\n", x);
return 0;
}

the program doesn't seem to terminate.
To me they seem to be more or less equivalent.
Why does it behave differently?


I don't know.
Which computer, operating system and compiler are you using?
Which compiler options are you using?

On my machine, x + 1 (and x < x + 1)
is evaluated using extended precision arithmetic
but x is rounded and stored as double precision
so x increments to 16777216.0 then never changes.
Nov 14 '05 #10
In article <JC*********************@newsc.telia.net>,
August Karlstrom <fu********@comhem.se> wrote:
If I change the example above to
You missed stdio.h ;-)
int main(void)
{
float x = 0.0;

while (x < x + 1) { x++; }
fprintf(stdout, "x = %f\n", x);
return 0;
} the program doesn't seem to terminate. To me they seem to be more or
less equivalent. Why does it behave differently?


Data point:

With the addition of stdio.h, it terminates for me on SGI IRIX,
using the native compiler or gcc. The termination point is 16777216.

--
History is a pile of debris -- Laurie Anderson
Nov 14 '05 #11
In article <JC*********************@newsc.telia.net>,
August Karlstrom <fu********@comhem.se> wrote:
E. Robert Tisdale wrote:
Jonathan Bartlett wrote:
Any time that you might want to increase the value of a float by one.
It could happen, right?
I think the problem with floats is that, depending on the magnitude of
the float, it may be a noop.

You think?
> cat main.c

#include <stdio.h>

int main(int argc, char* argv[]) {
float x = 0.0, y;
do {
y = x;
++x;
} while (y < x);
Old value of x has type float. New value of x is calculated with
possibly higher precision than float, but is then rounded to type float.
On typical implementations, 2^24 + 1 cannot be represented as a number
of type float and will be rounded down to 2^24, so your loop will finish
when y = 2^24.
fprintf(stdout, "x = %f\n", x);
//do {
// y = x;
// } while (y < ++x);
//fprintf(stdout, "x = %f\n", x);
return 0;
}
> gcc -Wall -std=c99 -pedantic -o main main.c
> ./main

x = 16777216.000000


As I thought. That is two to the 24th power.


If I change the example above to

int main(void)
{
float x = 0.0;

while (x < x + 1) { x++; }
fprintf(stdout, "x = %f\n", x);
return 0;
}

Increasing x is done using type float, so x will be stuck at 2^24, as
before. However, in the test "x < x+1", your compiler may evaluate x+1
with higher precision as float, for example double. In that case you
will always be comparing 2^24 < 2^24 + 1, which is always true. Your
loop doesn't finish, but x will be stuck on the same value.
Nov 14 '05 #12
E. Robert Tisdale wrote:
August Karlstrom wrote:
If I change the example above to

int main(void) {
float x = 0.0;

while (x < x + 1) { x++; }
fprintf(stdout, "x = %f\n", x);
return 0;
}

the program doesn't seem to terminate.
To me they seem to be more or less equivalent.
Why does it behave differently?

I don't know.
Which computer, operating system and compiler are you using?


I have an AMD Athlon XP machine with Fedora Core 3 and gcc 3.4.3.
Which compiler options are you using?


gcc -Wall -o test test.c
-- August

Nov 14 '05 #13
Walter Roberson wrote:
In article <JC*********************@newsc.telia.net>,
August Karlstrom <fu********@comhem.se> wrote:

If I change the example above to

You missed stdio.h ;-)


No I do include stdio.h, I just didn't show the whole file:

$ cat test.c
#include <stdio.h>

int main(void)
{
float x = 0.0;

while (x < x + 1) { x++; }

/* float x = 0.0, y; */
/* do { */
/* y = x; */
/* ++x; */
/* } while (y < x); */
/* fprintf(stdout, "x = %f\n", x); */
return 0;
}
-- August
Nov 14 '05 #14
Christian Bau wrote:
If I change the example above to

int main(void)
{
float x = 0.0;

while (x < x + 1) { x++; }
fprintf(stdout, "x = %f\n", x);
return 0;
}


Increasing x is done using type float, so x will be stuck at 2^24, as
before. However, in the test "x < x+1", your compiler may evaluate x+1
with higher precision as float, for example double. In that case you
will always be comparing 2^24 < 2^24 + 1, which is always true. Your
loop doesn't finish, but x will be stuck on the same value.


Okay, so in the first case we are comparing floats, x and y, and in the
second case we compare a float, x, to a number with higher precision, `x
+ 1'? Very subtle indeed.

-- August
Nov 14 '05 #15

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

Similar topics

8
by: Tom | last post by:
Has anyone ever seen a IComparer for floats the returns magnitude. i.e. instead of returning -1, it would return -5. To let you know HOW different the two numbers are. obviously for int it is a -...
43
by: J.K. Becker | last post by:
Hi there, I am trying to multiply doubles with floats (actually I tried every possible combination by now) and it never works (well, it does something but it is always wrong). I have no idea...
12
by: BGP | last post by:
I am working on a WIN32 API app using devc++4992 that will accept Dow Jones/NASDAQ/etc. stock prices as input, parse them, and do things with it. The user can just cut and paste back prices into a...
15
by: Michel Rouzic | last post by:
I tried making a function that would fill half of an array with random doubles that would go from -pi to +pi. Unfortunatly, all it ever returns is -pi. I haven't used an already existing random...
6
by: Mike P | last post by:
Why does this cause the error 'cannot implicitly convert type 'double' to 'float'? Can you not multiply doubles by floats without converting them all to the same datatype? fltPCRateStd =...
4
by: David Veeneman | last post by:
Are System.Double operators overloaded to perform epsilon comparisons, or do these comparisons have to be performed by the programmer. In other words, if I have two doubles, A and B, and I test "A...
6
by: godavemon | last post by:
I need to take floats and dump out their 4 byte hex representation. This is easy with ints with the built in hex function or even better for my purpose def hex( number, size ): s =...
7
by: SpreadTooThin | last post by:
I have some code... import array a = array.array('d') f = open('file.raw') a.fromfile(f, 10) now I need to convert them into floats (32 bit...) what do i do?
6
by: Pavel | last post by:
Hello, Does anyone know a (preferably open-source) multi-platform C or C++ library that would be able to write and read C/C++ doubles and floats to/from streambuf, char array or similar device...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.