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.
You can use
from __future__ import divisionto 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/3instead of1/3. (The1.0makes the first number a float rather than an integer, which makes division work right.)