Welcome!

Sign in with your CogSci, Facebook, Google, or Twitter account.

Or register to create a new account.

We'll use your information only for signing in to this forum.

Supported by

[solved] Division Returns Integer Instead of Float

XeonenXeonen Posts: 4
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

Solution

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

Comments

  • eduardeduard Posts: 973
    edited 1:19PM

    Hi,

    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).

    Eduard

Sign In or Register to comment.