zoukankan      html  css  js  c++  java
  • (转) python学习笔记6--fraction

    原文:https://blog.csdn.net/lemonwyc/article/details/37592883

    fraction模块提供有关有理数的算术表达和计算,实际上就是分数的表达和计算。python中的一个分数可以由以下几种方式构造出来:

    Fraction(numerator=0, denominator=1)  :第一个参数是分子,默认为0;第二个参数为分母,默认为1。比如Fraction(2)=2;Fraction()=0。

    Fraction(other_fraction) :从其他分数构造。

    Fraction(float) :从float构造,表达出的分数值与float在内存中的存储值对应,可能不够精确。

    Fraction(decimal) :从Decimla数构造。

    Fraction(string):从string构造。

    使用如下:

    1.  
      from fractions import *
    2.  
      from decimal import *
    3.  
       
    4.  
      #Construct a Fraction by numerator and denominator
    5.  
      print (Fraction(3)) #3
    6.  
      print (Fraction()) #0
    7.  
      print (Fraction(10,8)) #5/4
    8.  
       
    9.  
      #construct by other fraction
    10.  
      print (Fraction(5/4)) #5/4
    11.  
       
    12.  
      #construct by float
    13.  
      print (Fraction(2.5)) #5/2
    14.  
      print (Fraction(1.1)) #2476979795053773/2251799813685248
    15.  
       
    16.  
      #construct by decimal
    17.  
      print (Fraction(Decimal('2.5'))) #5/2
    18.  
       
    19.  
      #construct by string
    20.  
      print (Fraction('12/23')) #12/23


    另外,fraction和math中还有几个关于分数操作比较常见的函数

    limit_denominator(max=1000000):可以截取想要得到的分母最大值;

    floor(fraction):小于该分数的最大整数;

    ceil(fraction):大于该分数的最小整数;

    round(fraction):各版本略有不同,没具体分析,通常是最近的整数。

      1.  
        #test functions
      2.  
        print (Fraction('3.1415926').limit_denominator(1000)) #355/113
      3.  
        print (floor(Fraction(355,113))) #2
      4.  
        print (ceil(Fraction(355,113))) #3
      5.  
  • 相关阅读:
    今天18:40分左右一部价值500多块捷安特自行车被盗!
    利用ASP.net上传文件
    _desktop.ini
    Visual Studio .NET 设置移植工具
    审计厅的项目终于可以告一段落了
    Word2CHM Assistant(Word2CHM助手)V2.1.0 破解版
    最近比较烦!
    delphi 中 Format 用法总汇
    谈谈公司管理及需求方面的问题
    [待续]SQLSERVER无法访问远程服务器问题
  • 原文地址:https://www.cnblogs.com/liujiacai/p/9542488.html
Copyright © 2011-2022 走看看