400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

创新互联Python教程:fractions—-分数

fractions —- 分数

源代码 Lib/fractions.py

成都创新互联公司主营武陵网站建设的网络公司,主营网站建设方案,APP应用开发,武陵h5小程序开发搭建,武陵网站营销推广欢迎武陵等地区企业咨询


fractions 模块支持分数运算。

分数实例可以由一对整数,一个分数,或者一个字符串构建而成。

class fractions.Fraction(numerator=0, denominator=1)

class fractions.Fraction(other_fraction)

class fractions.Fraction(float)

class fractions.Fraction(decimal)

class fractions.Fraction(string)

第一个版本要求 numeratordenominator 是 numbers.Rational 的实例,并返回一个新的 Fraction 实例,其值为 numerator/denominator。 如果 denominator0 将会引发 ZeroDivisionError。 第二个版本要求 other_fraction 是 numbers.Rational 的实例,并返回一个 Fraction 实例且与传入值相等。 下两个版本接受 float 或 decimal.Decimal 的实例,并返回一个 Fraction 实例且与传入值完全相等。 请注意由于二进制浮点数通常存在的问题 (参见 浮点算术:争议和限制),Fraction(1.1) 的参数并不会精确等于 11/10,因此 Fraction(1.1)不会 返回用户所期望的 Fraction(11, 10)。 (请参阅下文中 limit_denominator() 方法的文档。) 构造器的最后一个版本接受一个字符串或 unicode 实例。 此实例的通常形式为:

 
 
 
 
  1. [sign] numerator ['/' denominator]

where the optional sign may be either ‘+’ or ‘-‘ and numerator and denominator (if present) are strings of decimal digits (underscores may be used to delimit digits as with integral literals in code). In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples:

 
 
 
 
  1. >>> from fractions import Fraction
  2. >>> Fraction(16, -10)
  3. Fraction(-8, 5)
  4. >>> Fraction(123)
  5. Fraction(123, 1)
  6. >>> Fraction()
  7. Fraction(0, 1)
  8. >>> Fraction('3/7')
  9. Fraction(3, 7)
  10. >>> Fraction(' -3/7 ')
  11. Fraction(-3, 7)
  12. >>> Fraction('1.414213 \t\n')
  13. Fraction(1414213, 1000000)
  14. >>> Fraction('-.125')
  15. Fraction(-1, 8)
  16. >>> Fraction('7e-6')
  17. Fraction(7, 1000000)
  18. >>> Fraction(2.25)
  19. Fraction(9, 4)
  20. >>> Fraction(1.1)
  21. Fraction(2476979795053773, 2251799813685248)
  22. >>> from decimal import Decimal
  23. >>> Fraction(Decimal('1.1'))
  24. Fraction(11, 10)

Fraction 类继承自抽象基类 numbers.Rational,并实现了该类的所有方法和操作。 Fraction 实例是可哈希的,并应当被视为不可变对象。 此外,Fraction 还具有以下属性和方法:

在 3.2 版更改: Fraction 构造器现在接受 float 和 decimal.Decimal 实例。

在 3.9 版更改: 现在会使用 math.gcd() 函数来正规化 numeratordenominator。 math.gcd() 总是返回 int 类型。 在之前版本中,GCD 的类型取决于 numeratordenominator 的类型。

在 3.11 版更改: Underscores are now permitted when creating a Fraction instance from a string, following PEP 515 rules.

在 3.11 版更改: Fraction implements __int__ now to satisfy typing.SupportsInt instance checks.

参见

numbers 模块

构成数字塔的所有抽象基类。


网站栏目:创新互联Python教程:fractions—-分数
分享地址:http://www.bluegullmedia.com/article/cogjhde.html

其他资讯

让你的专属顾问为你服务

0.0344s