3

I just wanted to know that is there a way of implementing ceil function without using if-else? With if-else (for a/b) it can be implemented as:

if a%b == 0:
    return(a/b)
else:
    return(a//b + 1)
Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38

3 Answers3

10

Simplest would be.

a//b + bool(a%b)

And just for safety,

b and (a//b + bool(a%b))

Cheers.

simplyharsh
  • 35,488
  • 12
  • 65
  • 73
6

Like this should work if they are integers (I guess you have a rational number representation):

a/b + (a%b!=0)

Otherwise, replace a/b with int(a/b), or, better, as suggested below a//b.

sashkello
  • 17,306
  • 24
  • 81
  • 109
6
-(-a//b)

Perhaps the simplest?

========================

*Edited per @Gilles's comment:

for an integer n,

floor(x)=n for x in [n, n+1)
ceil(y)=n+1 for y in (n, n+1]

So, floor(-y)=-n-1 for -y in [-n-1, -n),

and ceil(y)=-floor(-y)=n+1 for y in (n, n+1]

In Python, floor(a/b) = a//b. Thus ceil(a/b) = -(-a//b)

beares
  • 61
  • 1
  • 2