displaydisplayname
displaydisplayname

Reputation: 317

For any float number x,y,integer n, where const y=n-x, and 0<=x,y,n<=MAX_VALUE, is x+y==n always true?

For example:

const n=5;
const x=1.23;
const y=n-x;
document.write(x+y==n);

the code about prints true for n=5,x=1.23,y=5-1.23 (value after rounded). I think it is just a "lucky" case to be true because I think there may some case that n-x would round to something so that x+y would not be equal to n again. But I try using for loop to find some false case:

for(let i=0;i<100000;i++){
  const n=Math.floor(Math.random()*10000);
  const x=Math.random()*5000;
  const y=n-x;
  if(x+y!=n){
    document.write(x+","+y+","+n);
    break;
  }
}

and surprisingly don't print any exceptions for several times running.

So my question is, for any float number x,y,integer n, where const y=n-x, and o<=x,y,n<=MAX_VALUE, is x+y==n always true? If so, what is the reason? Is there any case that is false?

Side note: It seems that it is also true for x>n,eg:

for(let i=0;i<100000;i++){
      const n=Math.floor(Math.random()*10000);
      const x=10000+Math.random()*5000;
      const y=n-x;
      if(x+y!=n){
        document.write(x+","+y+","+n);
        break;
      }
}

but not in the case that x is negative:

for(let i=0;i<100000;i++){
      const n=Math.floor(Math.random()*10000);
      const x=Math.random()*-5000;
      const y=n-x;
      if(x+y!=n){
        document.write(x+","+y+","+n);
        break;
      }
}

What is the reason?

Upvotes: 3

Views: 92

Answers (1)

alias
alias

Reputation: 30428

No it isn't. Here's a counter-example:

const n=5847425060810559;
const x=87667.5;
const y=n-x;
document.write(x+y==n);
document.write("<br>lhs = " + (x+y) + "<br>rhs = " + n);

Upvotes: 1

Related Questions