Speed of execution of the functions ceil(),round(),floor() - page 2

 
pavlick_:

Why don't you cast to the long? Although you can overflow it too, but it's a lot easier to overflow Int.


Of course, you can cast long if you need to.

 
y=ceil(x);  -> y=(int)(x+1);

x=3;

y=3; y=4;

 
Nikolai Semko:

Of course, you can go long if you need to.

So you're advertising a way, it'll be copied stupidly. Generally, you can't cast like this without any checks, it's UB:

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
Maybe he'll sell the deposit, maybe he'll do something else ))
 
pavlick_ :

So you're advertising a way, it'll be bluntly copied. You can't cast like that without checking, it's UB:

Maybe the deposit will sell out, and maybe do something else ))).

I'm not advertising anything. I'm sharing an idea. That's what this forum and discussion is for.

 
Dmitry Fedoseev:

x=3;

y=3; y=4;


Right! thanks. I'll have to see what I can do about the ceiling.

 
y=ceil(x);  -> y=(int)(x+1);

Dmitry Fedoseev:

x=3;

y=3; y=4;

as an option, although not very pretty, but the speed is the same:

y=ceil(x);  -> y=(int)(x+0.999999999999999);
#define _ceil(x)  (int)((x)+0.999999999999999)

double x=3;
int y=_ceil(x);
 
 
Nikolai Semko:

as an option, although not very nice, but the speed is the same:

Then it would probably be better: x + 1 - DBL_MIN. Or x + 1 -DBL_EPSILON. I haven't checked it, try it.

Oh, and what about negative numbers? It should be different for ceil and floor

 
Alexey Navoykov:

Then it would probably be better: x + 1 - DBL_MIN. Or x + 1 -DBL_EPSILON. I haven't checked it, try it.

Oh, and what about negative numbers? It must be different for ceil and floor

DBL_MIN andDBL_EPSILON don't work - they are too small. Perhaps it makes sense to leave it at 0.999999999999999999 (16 nines - the maximum number of decimal points in double)

Yes, you're right - there must be a different algorithm for negative numbers. Thank you! I will make an addition in the first post.

Who is interested - can think how to solve the problem with negative numbers. I personally am not interested, as all my problems are related to positive numbers.

 
Nikolai Semko:

It probably makes sense to leave 0.99999999999999999999 (16 nines - the maximum number of decimal places in double)

void OnStart()
{
        Print((int)(3.0 + 0.9999999999999999));
}
Have you checked the result?
 

A100:

void OnStart()
{
        Print( (int)(3 + 0.9999999999999999));
}


Yes, but if:

x=3;
int Y=(int)ceil(x);
Print(Y);
Y=(int)(x+0.999999999999999);
Print(Y);

then it's fine. Miracles of the compiler. :))