Monday 18 December 2017

Force Python calculation in double





I want to print a double in Python. But it doesn't work, and I don't
know why.




My
code:



test = 3000 / (1500 *
2000)
print
str(test)


I always get
a 0 and not a 0.001 even if I do the
following:



test = 3000 / (1500 *
2000)

print '%.10f' %
test


I get a
0.000000000 and not
0.001.



How do I tell
Python that this should be a double?


class="post-text" itemprop="text">
class="normal">Answer



In Python
2.x you need to convert at least one of the operands to float, as integer division
results in truncated output in Python 2.x:



>>> 3000 / (1500 *
2000)

0
>>> 3000.0 / (1500 * 2000) # Or use
float(3000)
0.001
>>> float(3000) / (1500 *
2000)
0.001


Or
you can import division of Python 3.x in Python 2.x, where integer division results in
true
division:



>>> from
__future__ import division

>>> 3000.0 / (1500 *
2000)
0.001


Note
that this will affect the division in the whole module.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...