just a simple for loop from 2 to 4(including for with increments 0.1 and 0.01.

the problem is that when the increment is 0.1, the value of cur in last loop is 3.9; wheras, when increment=0.01 it is 4(as expected). all the variables are "double".

any idea or suggestion?

for(cur=alt;cur<=ust;cur=cur+0.1)
	{
		
		curf=cur*cur;

	printf("cur = %lf, prev=%lf , curf= %lf , prevf=%lf \n", cur,prev,curf,prevf);


		trap=(curf+prevf)*(cur-prev)/2;
			

		sum=sum+trap;
		prev=cur;
		prevf=curf;
		
	}

Recommended Answers

All 6 Replies

doubles can not be represented exactly in memory. The value of 0.1 may or may not be represented in memory as 0.100001 or something like that, and that's why incrementing 3.9 by 0.1 may cause the number to be greater than 4.0. There is little, if anything, you can do about it except convert the doubles to integers and use the integers in the loop.

doubles can not be represented exactly in memory. The value of 0.1 may or may not be represented in memory as 0.100001 or something like that, and that's why incrementing 3.9 by 0.1 may cause the number to be greater than 4.0

hmm. i see. i need to be precise on my work. actually i was using "double" type pf variable to be precise. thus what can be a solution to this?

I already mentioned one solution. using doubles just introduces inprecision. Maybe something like this:

// this might work if all you are interested in is one decimal place.  
int start; 
int stop = (int)(ust*10.0);
for(start = (int)(alt*10.0); start <= stop; start++)
{

}

I already mentioned one solution. using doubles just introduces inprecision. Maybe something like this:

// this might work if all you are interested in is one decimal place.  
int start; 
int stop = (int)(ust*10.0);
for(start = (int)(alt*10.0); start <= stop; start++)
{

}

hmm. that makes sense. however, i will deal with 4 or more decimal points. in that case i guess replacing 10 with 10000 should work.

Yes, but be careful not to overflow the integers. check limits.h to see the maximum value that can be stored in an integer with your compiler.

Yes, but be careful not to overflow the integers. check limits.h to see the maximum value that can be stored in an integer with your compiler.

allright. thank you very much ancient dragon.

i consider either calculating the number of loops that will be generated, so that i would deal with integer type, or the way you proposed.

thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.