Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fractions in Python

Is there anyway to compute a fraction, e.g. 2/3 or 1/2, in Python without importing the math module?

The code snippet is simple:

# What is the cube root of your number
n = float(raw_input('Enter a number: '))
print(n**(1/3))

Extraordinarily simple code, but everywhere I look it's telling me to import the math module. I just want to add that snippet into a bigger code I'm working on. I keep getting 1 as my answer because Python feels like 1/3 is 0 rather than .333333333. I could put .33333, but that's just a temporary fix and I want to know how to perform this very basic computation for future projects.

like image 804
01110100 Avatar asked Oct 06 '12 20:10

01110100


2 Answers

You can use from __future__ import division to make integer division return floats where necessary (so that 1/3 will result in 0.333333...).

Even without doing that, you can get your fractional value by doing 1.0/3 instead of 1/3. (The 1.0 makes the first number a float rather than an integer, which makes division work right.)

like image 198
BrenBarn Avatar answered Oct 16 '22 15:10

BrenBarn


There is a fractions module in the standard library that can perform various tasks on fractions. If you have a lot of computations on fractions, You can do them without converting them to float. http://docs.python.org/library/fractions.html

like image 42
yilmazhuseyin Avatar answered Oct 16 '22 15:10

yilmazhuseyin