python将⼩数转为分数_Python分数
python将⼩数转为分数
Python分数模块 (Python fractions module)
As we know, a fraction is a number which represents a whole number being divided into multiple parts. Python fractions module allows us to manage fractions in our Python programs.
众所周知,⼩数是⼀个数字,代表⼀个整数,它被分为多个部分。 Python分数模块允许我们在Python程序中管理分数。
管理分数 (Managing fractions)
In this Python post, we will manage fractions and perform various operations on them. Let’s get started.
在此Python帖⼦中,我们将管理分数并对其执⾏各种操作。 让我们开始吧。
创建分数 (Creating Fractions)
Fraction class in Python allows us to make its instance in various ways. Here is a sample program:
Python中的Fraction类允许我们以各种⽅式创建其实例。 这是⼀个⽰例程序:
import fractions
for num, decimal in [(3, 2), (2, 5), (30, 4)]:
fract = fractions.Fraction(num, decimal)
print('{}/{} = {}'.format(num, decimal, fract))
Let’s see the output for this program:
This means that we can easily convert a fraction into a String and manage it to debug in our prograns. Also, notice that in the last fraction 30/4, it was automatically resolved to the lowest form as 15/2.
让我们看⼀下该程序的输出:
这意味着我们可以轻松地将分数转换为String并对其进⾏管理以进⾏调试。 另外,请注意,在最后的分数30/4 ,它会⾃动解析为最低形式的15/2 。
We can also create a fraction from its String representation actually, like:
我们实际上还可以从其String表⽰形式创建⼀个分数,例如:
f = fractions.Fraction('2/7')
将⼩数转换为分数 (Converting Decimals to Fractions)
It is also possible to convert a decimal into a Fractional number. Let’s look at a code snippet:
也可以将⼩数转换为⼩数。 让我们看⼀下代码⽚段:
python代码转换import fractions
for deci in ['0.6', '2.5', '2.3', '4e-1']:
fract = fractions.Fraction(deci)
print('{0:>4} = {1}'.format(deci, fract))
Let’s see the output for this program:
Pretty easy to manage, right? But here is a catch, decimal values which cannot be exactly turned into a fraction might yield unexpected results like:
让我们看⼀下该程序的输出:
很容易管理,对不对? 但这是⼀个问题,不能完全转换为分数的⼗进制值可能会产⽣意外的结果,例如:
import fractions
for v in [0.1, 0.5, 1.5, 2.0]:
print('{} = {}'.format(v, fractions.Fraction(v)))
This will give an output as:
Noticed the issue with 0.1 representation? Let’s understand why this happens.
这将给出如下输出:
注意到0.1表⽰形式的问题? 让我们了解为什么会这样。
0.1表⽰的问题 (Issue with 0.1 representation)
As we clearly know, floats consist of two parts, an integer and an exponent part of which the base is taken to and multiplied by the integer part.
众所周知,浮点数由两部分组成:⼀个整数和⼀个指数部分,其底数取整数并乘以整数部分。
Base 10 makes working with math very easy as with Base 10, every number can be presented very easily. 0.5 can be represented as 5 x 10?¹. So, if we add numbers like 0.5 and 0.2, the result will be 0.7. But, the computers don’t work that way. Computers use Base 2 and not Base 10.
与使⽤Base 10⼀样, Base 10使数学运算⾮常容易,每个数字都可以很容易地显⽰出来。 0.5可以表⽰为5 x 10?¹ 。 因此,如果我们加上数字0.5和0.2,则结果将是0.7。 但是,计算机⽆法正常⼯作。 计算机使⽤Base 2⽽不是Base 10。
The issue arises with numbers which can be represented by Base 10 but not Base 2. Those numbers have to be rounded off to their closest equivalent. Considering the IEEE 64-bit floating point format, the closest number to 0.1 is 3602879701896397 x 2, and the closest number to 0.2 is 7205759403792794 x 2; adding them gives 10808639105689191 x 2, or an exact decimal value of 0.3000000000000000444089209850062616169452667236328125. Floating point numbers are generally
rounded for display.
问题出现在可以⽤Base 10表⽰但不能⽤Base 2表⽰的数字上。这些数字必须四舍五⼊到最接近的等值。 考虑到IEEE 64位浮点格式,最接近0.1的数字是3602879701896397 x 2 ,最接近0.2的数字是7205759403792794 x 2 ; 将它们相加得到10808639105689191 x 2 或确切的⼗进制值0.3000000000000000444089209850062616169452667236328125 。 浮点数通常会四舍五⼊以显⽰。
算术运算 (Arithmetic Operations)
We can also perform Arithmetic Operations quite easily with fractional numbers. Let’s see some examples here.
我们也可以很容易地⽤⼩数执⾏算术运算。 让我们在这⾥看⼀些例⼦。
执⾏数学运算 (Performing Mathematical operations)
Let’s construct a simple example that shows how to perform arithmetic operations with fractional numbers. Here is a sample program:
让我们构造⼀个简单的⽰例,展⽰如何使⽤⼩数执⾏算术运算。 这是⼀个⽰例程序:
import fractions
f_one = fractions.Fraction(3, 5)
f_two = fractions.Fraction(4, 9)
print('{} + {} = {}'.format(f_one, f_two, f_one + f_two))
print('{} - {} = {}'.format(f_one, f_two, f_one - f_two))
print('{} * {} = {}'.format(f_one, f_two, f_one * f_two))
print('{} / {} = {}'.format(f_one, f_two, f_one / f_two))
Let’s see the output for this program:
让我们看⼀下该程序的输出:
获取分数部分 (Getting parts of fractions)
It is possible to get only the numerator or the denominator of a fraction. Let’s look at a code snippet on how this can be done:
可能仅获得分数的分⼦或分母。 让我们看⼀下如何做到这⼀点的代码⽚段:
import fractions
fract = fractions.Fraction(221, 234) + fractions.Fraction(1, 2)
print("Numerator: {}".format(fract.numerator))
print("Denominator: {}".format(fract.denominator))
Let’s see the output for this program:
让我们看⼀下该程序的输出:
进⾏近似 (Making Approximations)
We can use the fractions module to approximate and round off a number to a rational value. Here is a sample program:
我们可以使⽤分数模块将数字近似并四舍五⼊为有理值。 这是⼀个⽰例程序:
import fractions
import math
print('Value of PI: {}'.format(math.pi))
pi_fraction = fractions.Fraction(str(math.pi))
print('Without limit: {}'.format(pi_fraction))
for num in [1, 6, 11, 60, 70, 90, 100]:
limited = pi_fraction.limit_denominator(num)
print('{0:8} = {1}'.format(num, limited))
Let’s see the output for this program:
The limit_denominator() function finds and returns the closest fraction that has the denominator with maximum value of num passed to it.
让我们看⼀下该程序的输出:
limit_denominator()函数查并返回最接近的分母,该分母具有最⼤的num分母。
四舍五⼊ (Rounding off fractions)
It is possible to round off fractions by the number of digits we want in the denominator. Let’s look at a code snippet:
可以通过分母中我们想要的位数四舍五⼊⼩数。 让我们看⼀下代码⽚段:
import fractions
fract = fractions.Fraction('25/3')
print('25/3 Rounded without limit : {}'.format(round(fract)))
print('25/3 Rounded to 1 digit    : {}'.format(round(fract, 1)))
print('25/3 Rounded to 2 digits  : {}'.format(round(fract, 2)))
Let’s see the output for this program:
Note that round() is a default Python’s interpreter function and doesn’t want any imports.
让我们看⼀下该程序的输出:
注意, round()是Python的默认解释器函数,不需要任何导⼊。
将数学与分数混合 (Mixing Math with Fractions)
In a final example, we will bring some functions from library and mix them with fractional representations here. Like flooring a fraction etc. Let’s look at a code snippet:
在最后⼀个⽰例中,我们将从库中引⼊⼀些函数,并将它们与⼩数表⽰形式进⾏混合。 像铺砌⼀个分数等。让我们看⼀下代码⽚段:
import math
from fractions import Fraction
print("25/2 Square root is:          {}".format(math.sqrt(Fraction(25, 4))))
print("28/3 Square root is:          {}".format(math.sqrt(Fraction(28,3))))
print("4102/1193 Floored to:          {}".format(math.floor(Fraction(4102, 1193))))
print("Pi/3 Sined Fraction:          {}".format(Fraction(math.sin(math.pi/3))))
print("Pi/3 Sined Fraction Limit Dn.: {}".format(Fraction(math.sin(math.pi/3)).limit_denominator(10)))
Let’s see the output for this program:
The floor() function just rounds of a decimal equivalent and provides the nearest integer.
让我们看⼀下该程序的输出:
floor()函数仅将⼩数点后⼀位舍⼊并提供最接近的整数。
结论 (Conclusion)
In this lesson, we studied how we can manage and use Fraction values in our Python program effectively.
在本课程中,我们研究了如何在Python程序中有效地管理和使⽤⼩数值。
Reference:
参考:
翻译⾃:
python将⼩数转为分数

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。