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 fractions

众所周知,小数是一个数字,代表一个整数,它被分为多个部分。 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:

python create fraction

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:

也可以将小数转换为小数。 让我们看一下代码片段:

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:

python decimal to fraction

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:

python 0.1 fraction issue

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:

python fraction arithmetic operations

让我们看一下该程序的输出:

获取分数部分 (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:

python fraction numerator denominator

让我们看一下该程序的输出:

进行近似 (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:

python fraction limit_denominator

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:

python fraction round

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 math 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:

python raction math

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: API Doc

参考: API文档

翻译自: https://www.journaldev.com/19226/python-fractions

python将小数转为分数

  • 13
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值