Possible error math.ceil ()

On Windows 7 Python 3.2, the following:

print(int(math.ceil(24/10))) 

gives me a "3" as expected.

On Windows Server with Active Python 2.5, it gives me a "2".

What is the problem and how can I solve it?

Here is my original code:

 number_of_pages = int(math.ceil(number_of_rows/number_of_rows_per_page)) 

Thanks,

Barry

+6
source share
4 answers

Python 2.x uses disivion truncation, so the answer on 24/10 is 2. ceil of 2 is still 2.

The fix is ​​to convert one of the operands to float:

 print(int(math.ceil(24.0/10))) 
+16
source

A quick read of programming languages ​​finds that an integer divided by integers returns

integer

  • python 2
  • java
  • C ++
  • c
  • FROM#
  • ruby
  • OCaml
  • e #
  • go
  • Fortran

floating point (asterisk means that there is an alternative syntax for returning an integer)

  • python 3 *
  • Javascript
  • Php
  • Perl *
  • dart *
  • Vbscript
  • vb.net *
  • Earl *
  • pascal *

something else

  • clojure (returns a relation if it cannot return an integer)

Choosing Python to change the semantics of the division operator was pretty controversial at the time. Returning an integer often surprises novice programmers and mathematicians, but experienced programmers often feel the same way when they find that separating two integers can return a floating point.

+3
source

Try the following: print(int(math.ceil(24/10.0))) , it will return the correct value. As mentioned, in Python 2.5, the expression 24/10 evaluates to 2 because it performs integer division.

+1
source

All you need to know is here http://www.python.org/dev/peps/pep-0238/ .

0
source

Source: https://habr.com/ru/post/910840/


All Articles