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 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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With