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

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

import fractionsfor 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 fractionsfor 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 fractionsf_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 fractionsfract = 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 mathprint('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 fractionsfract = 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 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 Fractionprint("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: API Doc

参考: API文档

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

python将小数转为分数

python将小数转为分数_Python分数相关推荐

  1. python怎么显示分数_python分数怎么表示什么

    Fraction函数是python中实现分数的一个模块(module),模块是由别人写的,并且可以被拿来直接使用的代码程序,包括类.函数以及标签的定义,是python标准函数库的一部分.使用是必须先插 ...

  2. python表示分数_python分数怎么表示什么

    Fraction函数是python中实现分数的一个模块(module),模块是由别人写的,并且可以被拿来直接使用的代码程序,包括类.函数以及标签的定义,是python标准函数库的一部分.使用是必须先插 ...

  3. python怎么显示分数_python分数怎么表示

    python分数怎么表示? Fraction函数是python中实现分数的一个模块(module),模块是由别人写的,并且可以被拿来直接使用的代码程序,包括类.函数以及标签的定义,是python标准函 ...

  4. python表示分数_python分数怎么表示

    python分数怎么表示? Fraction函数是python中实现分数的一个模块(module),模块是由别人写的,并且可以被拿来直接使用的代码程序,包括类.函数以及标签的定义,是python标准函 ...

  5. python分数_python 分数

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 我就废话不多说了,直接上代码吧! #! usrbinenv python# co ...

  6. python将list转为矩阵_python list转矩阵的实例讲解

    python list转矩阵的实例讲解 如下所示: #list转矩阵,矩阵列合并 x = [[1.2,2.2,1.4],[1.3,2.4,2.1],[1,1,0]] #表示有三个点,第一个点为(1,2 ...

  7. python将txt转为字符串_python做第一只小爬虫

    "受尽苦难而不厌,此乃修罗之路" 本文技术含量过低,请谨慎观看 之前用R语言的Rcurl包做过爬虫,给自己的第一感觉是比较费劲,看着看着发际线就愈加亮眼,最后果断丢之.不过好的是和 ...

  8. python将txt转为字符串_Python玩转《生僻字》

    茕茕孑立 沆瀣一气 踽踽独行 醍醐灌顶 绵绵瓜瓞 奉为圭臬 龙行龘龘 犄角旮旯 娉婷袅娜 涕泗滂沱 呶呶不休 不稂不莠 这首<生僻字>,考验的是"语文"硬实力.倘若实力 ...

  9. python保留小数点后位数_Python保留指定位数的小数

    Python保留指定位数的小数 1 '%.2f' %f 方法(推荐) f = 1.23456 print('%.4f' % f) print('%.3f' % f) print('%.2f' % f) ...

最新文章

  1. 学会Python后能找到什么工作,待遇如何?
  2. 常用的cmd快捷命令
  3. 面向对象的4个基本特征
  4. fanuc机器人编程手册_FANUC机器人示教编程:距离先执行指令功能介绍与使用方法
  5. Latex 安装与配置
  6. MeshLab怎么换背景颜色?
  7. 单片机及开发板的介绍
  8. 三本计算机专业考研211,一个三本学渣逆袭211的考研心得
  9. DDD基础 (实体 值对象)
  10. 旋转卡壳凸包(不用一下子就学完所有)
  11. 将Outlook中的邮件保存到本地磁盘,释放邮箱空间
  12. VMware Workstation Pro界面设置为中文界面
  13. 米家扫地机器人重置网络_米家扫地机器人骗局? 米家扫地机器人重置
  14. Verizon 宣布 48 亿美元收购雅虎核心业务
  15. 视频图像清晰度影响因素
  16. Yin算法应用(单片机\嵌入式)
  17. 软件测试工作三年薪资能拿20k往上吗?
  18. Leetcode学习之动态规划
  19. chariot iperf使用_网络性能测试软件Iperf与ixChariot有什么区别
  20. python哪些城市好就业_目前最全的python的就业方向

热门文章

  1. sql server2008 远程过程调用失败
  2. Java中volatile的作用以及用法
  3. [转载] 莫烦python学习笔记之numpy.array,dtype,empty,zeros,ones,arrange,linspace
  4. (数论)51NOD 1136 欧拉函数
  5. 16_使用开源项目下载文件
  6. Java知多少(84)图形界面之布局设计
  7. android开发学习笔记系列(6)--代码规范
  8. ecshop添加商品选择品牌时如何按拼音排序
  9. 《Velocity 模板使用指南》中文版[转]
  10. Learning Video Object Segmentation from Static Images