Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Supported by

[solved] Division Returns Integer Instead of Float

edited April 2016 in Miscellaneous

I'm using OpenSesame version 3.0.7 and xpyriment as my back-end. I can safely display numbers like 0.14 but when I try to divide 2 with 3, I get a rounded number. I've tried initiating the variable with a float but again when I did the division I got an integer value rounded down to the nearest integer.

var.mathTest = 2/3 results with 0
var.mathTest = 4/3 results with 1


There are three solutions to this problem, first one is using truediv module, second one is adding 0.0 to one of the variables in every division or converting these numbers to float and the third one is importing a different division schema from the "future" in other words Python 3.0.

The reason behind the problem is Python 2.7's basic mathematical functions, division rounds down numbers by default.

First Solution

from operator import truediv
a = truediv(1,3)
print a

Second Solution - A

a = 1/(3+0.0)
print a

Second Solution - B

n = 3
a = 1/float(n)
print a

Third Solution

from __future__ import division
a = 1/3
print a


  • edited 3:12AM


    Solution A can also just be written as a = 1/3.0.

    You're right. That's just the way Python2.x does divide. With python3.x this behaviour will change. Btw. Opensesame supports also python 3. So, if you start it explicitly with python3. You should get the desired behavior right away. However, currently many dependencies are not yet Python3 compatible (e.g. psychopy).


Sign In or Register to comment.