Why ceil function acting weird?


when the float point is very smal it’s not work correctly also when number is so big

These might be helpful:

2 Likes

thanks, but i can’t find the solution, in a codeforces problem i need to calculate ceil of a big number, how can i do that?

By not using float.

You should use decimal.Decimal

1 Like

i wonder if there is a way to set in python to use this by default?

I don’t think there is or there should be. float is faster and lighter.

If you really need it to be precise, you have options.

This is a common problem on almost every other language.

1 Like

And then they might have the same problem just a little later.

Really they should tells us more about what they’re doing, so that we can suggest a real proper solution.

2 Likes

I don’t see anything “incorrect” here. On your first example you have something like this:

>>> 1.00000000000000001
1.0
>>> math.ceil(_)  # (1)
1
>>> 1.0000000001
1.0000000001
>>> math.ceil(_)  # (2)
2

Probably, you expected (2) in both cases. But floating-point numbers have a fixed precision. So, if you put enough zeros before trailing 1 — the value will be eventually rounded to 1.0. It’s float with an integer value (floor() equals to cell()).

Similarly your last example:

>>> 2832139218378291759861231213.1  # (3)
2.8321392183782917e+27
>>> _.is_integer()
True
>>> math.ceil(2832139218378291759861231213.1)
2832139218378291710804361216

You put too much digits in, so your input was rounded and you get some unexpected (for you) floating-point integer value at (3).

Indeed.

You will have similar with the decimal module, though it’s default precision is bigger (28 decimal significant digits vs 15-17 for floats):

>>> import decimal, math
>>> decimal.getcontext().prec = 5
>>> +decimal.Decimal('1.00000000001')
Decimal('1.0000')
>>> math.ceil(+decimal.Decimal('1.00000000001'))
1
>>> +decimal.Decimal('123445.1')
Decimal('1.2345E+5')
>>> math.ceil(+decimal.Decimal('123445.1'))
123450
1 Like