Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems of float or double calculations being not quite exact.

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Hi, I am trying to write a program that works out pythagoreon triples. Could someone help me so that the calculations give the correct answer?


#include <stdio.h>
#include <math.h>
#define N 20

int main(void) {
int i,j,intsum; float sum;
for (i=1; i <=N; ++i) {
for (j=1; j <= N; ++j) {
sum = sqrt(i*i + j*j);
intsum = sum; /* integer part of sum only */
/* if no fractional part, then perfect square*/

if ( (sum - intsum) == 0)
if (i<j)
if (intsum % 2 !=0)
printf(&quot;%d %d %d\n&quot;, i, j, intsum);

}
}
return 0;
}



 
Looks fine.

May be some platforms have problem with:
float sum; Try it make double sum;
Also intsum = (int)sum;
and most important:
if ((sum - (double)intsum) == 0.)

If it will not help post yours output.
 
Guys,
you can not say
if(sum - (double)intsum == 0.0) no no!

double delta = 0.005; // use your value here
then always compare those two with your delta!
x - y < delta in this fashion.

Don't forget that float or double keeps approximation to the real value, for example float x=1.0; could be 0.999999 in fact
 
#include <stdio.h>
#include <math.h>
#define N 20

int main(void) {
int i,j,intsum; float sum;
for (i=1; i <=N; ++i) {
for (j=1; j <= N; ++j) {
sum = (float)sqrt(i*i + j*j);
intsum = (int)sum; /* integer part of sum only */
/* if no fractional part, then perfect square*/

if ( (sum - intsum) == 0)
if (i<j)
if (intsum % 2 !=0)
printf(&quot;%d %d %d\n&quot;, i, j, intsum);

}
}
return 0;
}

Now it will compile without any warnings.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top