1

Well, I tried out a couple of lines but it seems not to work.

double equation= ( ((double)avg-(double)cur_avg) / (1/(double)n) );
cout<<"equation is "<<equation<<endl;
lld needed = ceil(equation);
cout<<"needed is "<<needed<<endl;

Here avg and n are integers of type long long int. And cur_avg is already a double. Also avg=4, n=5 and cur_avg=3.4 . The output in the terminal reads as follows:

output:
equation is 3
needed is 4

Now, my question is if "equation" is 3 then ceil(equation) should have been 3 as well, but why it reads 4 then?
In short, what I require is this:

output:
equation is 3
needed is 3

Also, how to modify the above code snippet to get this result?

Edit:

Thank you Sebastian for proposing the solution in the comments.

An explanation of this behavior could be found here

A probable solution is to subtract a small epsilon when calling ceil:

double equation= ( ((double)avg-(double)cur_avg) / (1/(double)n) );
cout<<"equation is "<<equation<<endl;
lld needed = ceil(equation - .000001);
cout<<"needed is "<<needed<<endl;
  • 1
    I don't get your math. 4-3.4 is 0.6. 1/5 is 0.2. 0.6/0.2 is 3.Ceiling of 3 is three. What makes you expect 4? Ceil is the the lowest integer which is identical or higher as the input. If it were e.g. 3.0001 you'd surely get 4, but it is not. – Yunnosch Apr 05 '20 at 04:52
  • 1
    Apart from that, have a look at https://stackoverflow.com/questions/588004/is-floating-point-math-broken, which means that if `equation` is be 2.999999999 or 3.00000001, it would be shown as 3 in both case and result in either 3 or 4 for the `ceil()`. – Yunnosch Apr 05 '20 at 04:55
  • @Yunnosch I am not expecting 4. The output is giving 4. what I am expecting is 3. Btw, I am satisfied with the question proposed by Miles Budnek and the link you proposed in your second comment. But I don't think it's a duplicate. I would appreciate any answer regarding an alternative approach to solve this problem. I have modified the question so that it's not confusing anymore. – Mr_Somebody Apr 05 '20 at 07:00
  • You could subtract a small epsilon when calling ceil: lld needed = ceil(equation - .000001); – Sebastian Apr 05 '20 at 07:11
  • 1
    @Sebastian Thank you, this solves the purpose. Can you please, post it as an answer, along with https://stackoverflow.com/questions/588004/is-floating-point-math-broken this link as an explanation, so that I can mark it as accepted. – Mr_Somebody Apr 05 '20 at 07:57
  • @Mr_Somebody the question has already been closed by the site admins. But I am glad that it worked. You could edit your question and mention the correct solution – Sebastian Apr 05 '20 at 08:01

0 Answers0