简体   繁体   中英

Fractions in Python

Is there anyway to compute a fraction, eg 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

Simply add a decimal and fraction part to cast the operation to a float:

>>> n=float(raw_input('Enter a number: ')); print n**(1.0/3)
Enter a number: 2
1.25992104989

Or, use float explicitly:

>>> n=float(raw_input('Enter a number: ')); print n**(float(1)/3)
Enter a number: 2
1.25992104989

Or, use Python 3's style of division:

>>> from __future__ import division
>>> n=float(raw_input('Enter a number: ')); print n**(1/3)
Enter a number: 2
1.25992104989

Any of those three methods works. I prefer the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM