This question already has answers here:
Using integer division in Python
(2 answers)
Closed 8 years ago.
Basically i made this program to practice python ( i am a complete noob at it), i am quite enjoying python, as my first programming langauge ever learnt or in the process of i feel very accomplished when completeing a program that works ( even if it is hello world). So anyways, i made a small program using techniques i had learnt from books and stuff from the internet and i have an issue, the program works fine, without problems but at the end there is a division where it justr goes wrong, it cannot divide anything unless it makes a whole number (eg. 100/20=5 but if i did 20/100 it would equel 0 and not 0.2), this also effects it if the number is going to be negative it just panics. i tried 15/20 to see if it was rounding but it still said 0.Any help would be fantastic ^_^
here is the code:
a=100
b=50
c=10
z=110
o=5
zoo=z+o+o
print "What is the value of zoo if:"
print "z=110"
print "o=5"
print "zoo=z+o+o"
import time
time.sleep(5)
print zoo,"of course!"
import time
time.sleep(1)
print "Wait..",a+b-(c)*3,"is the same as zoo except we just did it there using other code!"
import time
time.sleep(3)
print "We did it using 100+50-(10)*3 which then adds to zoo or 120!"
import time
time.sleep(3)
print "were gonna try something fun now!"
import time
time.sleep(2)
print "Please pick a number:"
number=int(raw_input())
print "and another:"
another=int(raw_input())
print "the two numbers you chose multiplied together makes",number*another
import time
time.sleep(2)
print "ok now were going to take your two numbers and divide them"
print "Your two numbers divided=",number/another
import time
time.sleep(1)
print "Ok im bored now, im going to go, have a nice day ^_^"
and here is the awnser with a problem:
What is the value of zoo if:
z=110
o=5
zoo=z+o+o
120 of course!
Wait.. 120 is the same as zoo except we just did it there using other code!
We did it using 100+50-(10)*3 which then adds to zoo or 120!
were gonna try something fun now!
Please pick a number:
15
and another:
20
the two numbers you chose multiplied together makes 300
ok now were going to take your two numbers and divide them
Your two numbers divided= 0
Ok im bored now, im going to go, have a nice day ^_^
oh and im on python 2.7.6
Add above this line:
print "Your two numbers divided=",number/another
this code:
number, another = number + .0, another + .0
The reason your code doesn't work is because you're using int's. When you divide with integers, they return an integer or a whole number. You need to convert the numbers to floats by adding .0 to the numbers. This will allow you to get absolute division results.
You can add
from __future__ import division
at the top of your file. Then the default division strategy will be what you expect, i.e. floating point division. Python 2.7 does integer division by default.
The / quotient of two int's, in Python 2.x, is an int.
The / quotient of one int and one float, in Python 2.x, is a float.
The / quotient of two floats, in Python 2.x, is a float.
The / quotient of two int's, in Python 3.x, is a float.
The / quotient of one int and one float, in Python 3.x, is a float.
The / quotient of two floats in Python 3.x, is a float.
The // quotient of two int's, in Python 3.x, is an int.
The // quotient of one int and one float, in Python 3.x, is a whole-number float.
The // quotient of two floats in Python 3.x, is a whole-number float.
In Python 2.x, you can "from __future__ import division" at the top of your module, to get the 3.x behavior.
So since you're using 2.x, you probably should either "from __future__ import division" at the top of your module, or convert one or both of your int's to float with float(int_var) prior to / division.
To add to all answers. In some languages (including python) division operator result depends on value types being used e.g.:
>>> 1 / 2 # integer divided by integer
0
>>> 1.0 / 2 # float divided by integer
0.5
15/20 = 0 when performing an integer division since the result is less than 1. Therefore it truncates to 0.
// is used for dividing integers and / for floats- you are using the wrong operator so you get an incorrect result:
>>> 15 / 20
0
>>> 15 // 20
0.75
You can fix this by adding from from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division- so just do what you are doing and it will return the expected result:
>>> from __future__ import division
>>> 15 / 20
0.75
I would use the above solution, with the import; but there are other ways. Another option would be making at least one of the operands a float, e.g. float(number) / another.
>>> number = 15
>>> another = 20
>>> float(number) / another
0.75
The above works because the result of the division depends on value types being used, in Python.
Related
Hey i'm a little noob still but i'm playing around with python and i want to round D to it's nearest decimal, C and H are fixed and D is the rawinput, the whole answer should be rounded but i keep getting decimals,i want this formula :
Q = Square root of [(2 * C * D)/H]
her's my code:*
import math
C=50
H=30
D=int(raw_input())
a=int(round(D))
Q= math.sqrt(2*C*a/H)
print Q
if i enter 100 i get 18.24
i just want it to be 18
i would really appreciate your help, thanks
import math
C = 50
H = 30
a = int(raw_input())
# prints as a float
# Q = round(math.sqrt(2 * C * a / H), 0)
# prints as an int
Q = int(round(math.sqrt(2 * C * a / H), 0))
print Q
Your code appears to be rounding in the wrong place. You're rounding the input a, which was already the integer D. You're not rounding the result of the square root Q, which is a float.
Note that you're code actually has an extra rounding step you may not intend in it. When you divide two integers in Python 2, you'll get another integer, even if the computation should have had a remainder. You get floor division, always rounding towards negative infinity, not to the nearest integer (so e.g. 9/10 is 0). In your code, 2*C*a is an integer, since all values you're multiplying are, and so when you divide by h (another integer), it's going to round the division off. In the case you gave where you entered 100 as the user input, you'll get 333 as the result of the division instead of the more precise 333.3333333333333. This in turn makes your square root calculation give a different value (18.24828759089466 instead of 18.257418583505537).
Anyway, you probably want to use floating point values everywhere except maybe at the end when you round off the value before printing it. You almost certainly don't want to be using integer math by accident as your current code does. One way to do that is to turn one of your constant values into a float, and move the rounding to the end:
C=50.0 # make the calculations use floats, rather than ints
H=30
D=int(raw_input()) # no need for `a` anymore, we're rounding later instead
Q= int(round(math.sqrt(2*C*D/H))) # round after taking the square root, not before
An alternative to using C=50.0 is to put from __future__ import division at the top of your file, which tells Python that you want division between integers to return a float. That's the default behavior in Python 3, and it's much nicer most of the time. If you specifically want "floor" division, you can explicitly ask for it with the // operator. You might also consider actually using Python 3, rather than making do with Python 2's forwards compatibility features.
I made a xlrd to json parsing script, which doesn't divide variables. It always returns zero... the code which I am using to divide the variables is:
if not row_values[2]:
key['nr_one'] = 0
else:
key['nr_one'] = int(row_values[2])
if not row_values[4]:
key['nr_two'] = 0
else:
key['nr_two'] = int(row_values[4])
try:
key['perc'] = float(key['nr_two']/key['nr_one']*100)
except ZeroDivisionError:
key['perc'] = 0
I have printed the following code at the end of the script:
print('one')
print(key['nr_one'])
print('two')
print(key['nr_two'])
print('perc')
print(key['perc'])
This returns:
one
103386547
two
135680054
perc
0.0
So. I don't understand why the division fails and returns 0? Could someone please help me format a good way to calculate the percentage
it should be float(key['nr_two']) /key['nr_one']*100
Integer division is like this :
1/3 #=> 0
The easiest way to understand this result is not as a fraction, but as the answer to the question "How many times do 3 fit in 1?".
So 0 multiplied by 100 is still :
1/3 * 100 #=> 0
You need
100.0*1/3 #=> 33.333333
For your code :
key['perc'] = 100.0*key['nr_two']/key['nr_one'] (without using float(...))
It returns :
76.1987808465937
NOTE: You really need to type 100.0 (a float), not just 100 (an int). You'd get 76 otherwise.
key['nr_two'] is integer and so is key['nr_one']. So when they are divided, the result is forced to be an integer in Python 2x versions (in Python 3x this limitation does not exist and your code would run just fine). What you therefore get, is 0, which is later multiplied by 100, so still 0 but float, 0.0.
To achieve float division in python 2.x you can just add:
from __future__ import division
This way you will not need to convert your numbers each time you divide them.
This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
I'm trying to calculate 27^(1/3) = 3. But it turns out not as expected.
>>> 27 ** (1/3)
1
>>> 27 ** (1/3.)
3.0
Firstly, why the first calculation will result in 1, is it because 1/3 is casted to an int so it equals zero?
Secondly, what does the '.' means in Python in general, could I append a dot to any number in order to cast it from int to double?
Thanks.
Firstly, why the first calculation will result in 1, is it because 1/3
is casted to an int so it equals zero?
Yes, that's exactly it.
what does the '.' means in Python in general, could I append a dot to
any number in order to cast it from int to double?
The . is explicitly making the number a float as 1.0 would be opposed to just 1.
You experience integer division in python 2.
in python 2:
>>> 2/3
0
In python 3:
>>> 2/3
0.6666666
If you want the python3 behaviour in python2 you can do
from __future__ import division
as your first import.
For the integer division, use
>>> 2 // 3
0
Or you can use 2.0 / 3.0 to use floats.
In python 2.x, dividing integers defaults to floor division, so any non-integer quotient automatically rounds down to the nearest integer for example
>>> 1/3
0
>>> 5/2
2
So when you try to calculate 27 ** (1/3) you are just calculating 27 ** 0
There are numerous workarounds to the problem, the simplest way would be to just use floating points in the exponent - (1.0/3.0), or even just (1/3.0). However, if you were to be doing a lot of these calculations it might become annoying to constantly type out all the numbers in floating point form. In this case, you could use the future module to utilize Python 3.x division behavior, which always results in a floating point value:
>>> from __future__ import division
>>> 1/3
0.3333333333333333
This way the calculation will never default to floor division. And if at some point you want floor division in the same program, you can just use the // operator to get behavior similar to python 2.x integer division, like so:
>>> 1//3
0
This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 7 years ago.
I can't seem to find the answer to this on this site, though it seems like it would be common enough. I am trying to output a double for the ratio of number of lines in two files.
#Number of lines in each file
inputLines = sum(1 for line in open(current_file))
outputLines = sum(1 for line in open(output_file))
Then get the ratio:
ratio = inputLines/outputLines
But the ratio always seems to be an int and rounds even if I initialize it like:
ratio = 1.0
Thanks.
In python 2, the result of a division of two integers is always a integer. To force a float division, you need to use at least one float in the division:
ratio = float(inputLines)/outputLines
Be careful not to do ratio = float(inputLines/outputLines): although that results in a float, it's one obtained after doing the integer division, so the result will be "wrong" (as in "not what you expect")
In python 3, the integer division behavior was changed, and a division of two integers results in a float. You can also use this functionality in python 2.7, by putting from __future__ import division in the begging of your files.
The reason ratio = 1.0 does not work is that types (in python) are a property of values, not variables - in other words, variables don't have types.
a= 1.0 # "a" is a float
a= 1 # "a" is now a integer
Are you using Python 2.x?
Try using
>>> from __future__ import division
>>> ratio = 2/5
0.4
to get a float from a division.
Initializing with ratio = 1.0 doesn't work because with ratio = inputLines/outputLines you are re-assigning the variable to int, no matter what it was before.
Indeed, Python 2 returns an integer when you divide an integer. You can override this behaviour to work like in Python 3, where int / int = float by placing this at the top of your file:
from __future__ import division
Or better yet, just stop using Python 2 :)
You need to cast one of the terms to a floating point value. Either explicitly by using float (that is ratio = float(a)/b or ratio=a/float(b)) or implicitly by adding 0.0: ratio = (a+0.0)/b.
If using Python 2 you can from __future__ import division to make division not be the integral one but the float one.
Very basic question. If I set products as 3 and parcels as 2, I get 1. How do I have the last line print 1.5, a decimal, instead of simply 1?
products = raw_input('products shipped? ')
parcels = raw_input('parcels shipped? ')
print "Average Number of products per parcel"
print int(products) / int(parcels)
print float(products) / float(parcels)
If you want real numbers, use float, which represents real numbers. Don't use integers.
In Python 3 you'll get this automatically.
In Python 2 you can do from __future__ import division, then dividing two integers will result in a floating point number.
In either case you can use // instead of / if you decide you really needed an integer result instead. That works in Python 2 even if you don't do the import.
You can also convert either or both of the numbers to float to force a floating point result.
If you want the full decimal value use the below,
from decimal import Decimal
print Decimal(products) / Decimal(parcels)