-3

I have this question:

We claim that it is unsafe to use equality testing with floating point numbers because the arithmetic operations introduce rounding errors which mean that two numbers which ought to be equal are not.

For this program, you should pick a number N, and write a program to show for which of the integers x between 1 and 1000 the equality (x+1)/N = (x/N) + (1/N) fails

    #include <stdio.h>

int main () {
int x;
float N = 50;

for (x=0; x<1001; x++) {
  if ((x+1)/N != (x/N) + (1/N)) 
    {
     printf("%i\n",x); 
    }
 }
}

Is this correct?

Thanks.

  • 10
    Hello and welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist). You might also want to learn what a [SSCCE](http://sscce.org/) is. – Some programmer dude Oct 29 '13 at 18:35
  • Surely if your professor wants you to write this in C, you are expected to have at least a minimal understanding of how to write a C program. If you don't, your TA should be able to help you. – mah Oct 29 '13 at 18:46
  • Come on, don't be ironic, its his first question in the site... @LivingHealhty, we are not supposed to ask homework questions here, and wait to get answers including source code. Show us what you have tried so far, and we will give you some hints... – Rontogiannis Aristofanis Oct 29 '13 at 18:53
  • @LivingHealthy: Wait a minute - you're being given an assignment in a language that's different from the language the class is teaching? Did this class have a C prerequisite? – John Bode Oct 29 '13 at 19:10
  • Have you tried compiling it? Tried running it? Did it work as expected? – Some programmer dude Oct 30 '13 at 16:03
  • Also you should read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Some programmer dude Oct 30 '13 at 16:04
  • I'm not exactly sure what to expect :/ – Living Healthy Oct 30 '13 at 20:24

1 Answers1

0

Your program is wrong. It should start with x=1 instead of x=0.

But beside that, you should pick two examples (one that has been printed by the program and one that hasn’t) and calculate them by hand. With just pen and paper and the IEEE 754-1985 rules. Then print both sides of the equation and compare them to your hand-computed results.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121