Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write this without so many floats?

Tags:

python

float(float(1)/float(i) * float(score))
like image 883
TIMEX Avatar asked Jan 27 '26 02:01

TIMEX


2 Answers

Assuming Python 2.x: 1.0 / i * score

The main case you need to worry about is the division because in Python 2.x, division is defaulted to integer division. In order to have floating-point division, either the dividend or divisor needs to be a float, hence the 1.0. Thus, 1.0/i will be a float, and multiplying a float by score (which can either be an integer or float) will result in another floating-point number.

In python 3.x, however, division defaults to floating-point division, so 1 / i * score would work.

What you want is simply float(score)/i in Python2. If one operand is a float, then the result will be a float too ,so code like score/float(i) or 1.0*score/i works as well.

You can also put from __future__ import division at the top of your .py file and you have float division by default. This means you can write score/i and it will be a float, like in Python3.

like image 26
Jochen Ritzel Avatar answered Jan 28 '26 16:01

Jochen Ritzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!