Python fractions模块 —— 分数相关函数

简介: Python fractions模块 —— 分数相关函数

这是一简单的模块,搞不懂python为什么不把它并入math模块?

>>> import fractions
>>> fractions.__all__
['Fraction', 'gcd']
>>> fractions.gcd(12,18)
Warning (from warnings module):
  File "<pyshell#2>", line 1
DeprecationWarning: fractions.gcd() is deprecated. Use math.gcd() instead.
6
>>> fractions.gcd(14,6)
2
>>> import math
>>> math.gcd(14,6)
2
>>> 

一共就俩,其中一个最大公约数函数gcd()还不推荐使用,用math中的gcd替代。




fractions模块中的类Fraction


class Fraction(numbers.Rational)
 |  Fraction(numerator=0, denominator=None, *, _normalize=True)
 |  
 |  This class implements rational numbers.
 |  
 |  In the two-argument form of the constructor, Fraction(8, 6) will
 |  produce a rational number equivalent to 4/3. Both arguments must
 |  be Rational. The numerator defaults to 0 and the denominator
 |  defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
 |  
 |  Fractions can also be constructed from:
 |  
 |    - numeric strings similar to those accepted by the
 |      float constructor (for example, '-2.3' or '1e10')
 |  
 |    - strings of the form '123/456'
 |  
 |    - float and Decimal instances
 |  
 |    - other Rational instances (including integers)
 |  
 |  Method resolution order:
 |      Fraction
 |      numbers.Rational
 |      numbers.Real
 |      numbers.Complex
 |      numbers.Number
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __abs__(a)
 |      abs(a)
 |  
 |  __add__(a, b)
 |      a + b
 |  
 |  __bool__(a)
 |      a != 0
 |  
 |  __ceil__(a)
 |      math.ceil(a)
 |  
 |  __copy__(self)
 |  
 |  __deepcopy__(self, memo)
 |  
 |  __divmod__(a, b)
 |      (a // b, a % b)
 |  
 |  __eq__(a, b)
 |      a == b
 |  
 |  __floor__(a)
 |      math.floor(a)
 |  
 |  __floordiv__(a, b)
 |      a // b
 |  
 |  __ge__(a, b)
 |      a >= b
 |  
 |  __gt__(a, b)
 |      a > b
 |  
 |  __hash__(self)
 |      hash(self)
 |  
 |  __le__(a, b)
 |      a <= b
 |  
 |  __lt__(a, b)
 |      a < b
 |  
 |  __mod__(a, b)
 |      a % b
 |  
 |  __mul__(a, b)
 |      a * b
 |  
 |  __neg__(a)
 |      -a
 |  
 |  __pos__(a)
 |      +a: Coerces a subclass instance to Fraction
 |  
 |  __pow__(a, b)
 |      a ** b
 |      
 |      If b is not an integer, the result will be a float or complex
 |      since roots are generally irrational. If b is an integer, the
 |      result will be rational.
 |  
 |  __radd__(b, a)
 |      a + b
 |  
 |  __rdivmod__(b, a)
 |      (a // b, a % b)
 |  
 |  __reduce__(self)
 |      Helper for pickle.
 |  
 |  __repr__(self)
 |      repr(self)
 |  
 |  __rfloordiv__(b, a)
 |      a // b
 |  
 |  __rmod__(b, a)
 |      a % b
 |  
 |  __rmul__(b, a)
 |      a * b
 |  
 |  __round__(self, ndigits=None)
 |      round(self, ndigits)
 |      
 |      Rounds half toward even.
 |  
 |  __rpow__(b, a)
 |      a ** b
 |  
 |  __rsub__(b, a)
 |      a - b
 |  
 |  __rtruediv__(b, a)
 |      a / b
 |  
 |  __str__(self)
 |      str(self)
 |  
 |  __sub__(a, b)
 |      a - b
 |  
 |  __truediv__(a, b)
 |      a / b
 |  
 |  __trunc__(a)
 |      trunc(a)
 |  
 |  as_integer_ratio(self)
 |      Return the integer ratio as a tuple.
 |      
 |      Return a tuple of two integers, whose ratio is equal to the
 |      Fraction and with a positive denominator.
 |  
 |  limit_denominator(self, max_denominator=1000000)
 |      Closest Fraction to self with denominator at most max_denominator.
 |      
 |      >>> Fraction('3.141592653589793').limit_denominator(10)
 |      Fraction(22, 7)
 |      >>> Fraction('3.141592653589793').limit_denominator(100)
 |      Fraction(311, 99)
 |      >>> Fraction(4321, 8765).limit_denominator(10000)
 |      Fraction(4321, 8765)
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  from_decimal(dec) from abc.ABCMeta
 |      Converts a finite Decimal instance to a rational number, exactly.
 |  
 |  from_float(f) from abc.ABCMeta
 |      Converts a finite float to a rational number, exactly.
 |      
 |      Beware that Fraction.from_float(0.3) != Fraction(3, 10).
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(cls, numerator=0, denominator=None, *, _normalize=True)
 |      Constructs a Rational.
 |      
 |      Takes a string like '3/2' or '1.5', another Rational instance, a
 |      numerator/denominator pair, or a float.
 |      
 |      Examples
 |      --------
 |      
 |      >>> Fraction(10, -8)
 |      Fraction(-5, 4)
 |      >>> Fraction(Fraction(1, 7), 5)
 |      Fraction(1, 35)
 |      >>> Fraction(Fraction(1, 7), Fraction(2, 3))
 |      Fraction(3, 14)
 |      >>> Fraction('314')
 |      Fraction(314, 1)
 |      >>> Fraction('-35/4')
 |      Fraction(-35, 4)
 |      >>> Fraction('3.1415') # conversion from numeric string
 |      Fraction(6283, 2000)
 |      >>> Fraction('-47e-2') # string may include a decimal exponent
 |      Fraction(-47, 100)
 |      >>> Fraction(1.47)  # direct construction from float (exact conversion)
 |      Fraction(6620291452234629, 4503599627370496)
 |      >>> Fraction(2.25)
 |      Fraction(9, 4)
 |      >>> Fraction(Decimal('1.47'))
 |      Fraction(147, 100)
 |  
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |  
 |  denominator
 |  
 |  numerator
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __abstractmethods__ = frozenset()
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from numbers.Rational:
 |  
 |  __float__(self)
 |      float(self) = self.numerator / self.denominator
 |      
 |      It's important that this conversion use the integer's "true"
 |      division rather than casting one side to float before dividing
 |      so that ratios of huge integers convert without overflowing.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from numbers.Real:
 |  
 |  __complex__(self)
 |      complex(self) == complex(float(self), 0)
 |  
 |  conjugate(self)
 |      Conjugate is a no-op for Reals.
 |  
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from numbers.Real:
 |  
 |  imag
 |      Real numbers have no imaginary component.
 |  
 |  real
 |      Real numbers are their real component.


函数实例在上述帮助中有......混一篇凑凑数 ^_^


目录
相关文章
|
2月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
410 7
|
2月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
234 1
|
2月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
342 1
|
2月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
288 0
|
2月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
198 0
|
3月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
288 101
|
3月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
238 99
|
3月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
207 98
|
2月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
412 4
|
2月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
328 0

推荐镜像

更多