floattointpython
① python 如何控制輸出的小數長度
Python裡面小數點長度精度控制方法:
一、要求較小的精度
將精度高的浮點數轉換成精度低的浮點數。
1.round()內置方法
這個是使用最多的,剛看了round()的使用解釋,也不是很容易懂。round()不是簡單的四捨五入的處理方式。
For the built-in types supporting round(), values are rounded to the
closest multiple of 10 to the power minus ndigits; if two multiples are equally
close, rounding is done toward the even choice (so, for example, both round(0.5)
and round(-0.5) are 0, and round(1.5) is 2).
>>> round(2.5)
2
>>> round(1.5)
2
>>> round(2.675)
3
>>> round(2.675, 2)
2.67
round()如果只有一個數作為參數,不指定位數的時候,返回的是一個整數,而且是最靠近的整數(這點上類似四捨五入)。但是當出現.5的時候,兩邊的距離都一樣,round()取靠近的偶數,這就是為什麼round(2.5)
=
2。當指定取捨的小數點位數的時候,一般情況也是使用四捨五入的規則,但是碰到.5的這樣情況,如果要取捨的位數前的小樹是奇數,則直接舍棄,如果偶數這向上取捨。看下面的示例:
>>> round(2.635, 2)
2.63
>>> round(2.645, 2)
2.65
>>> round(2.655, 2)
2.65
>>> round(2.665, 2)
2.67
>>> round(2.675, 2)
2.67
2. 使用格式化
效果和round()是一樣的。
>>> a = ("%.2f" % 2.635)
>>> a
'2.63'
>>> a = ("%.2f" % 2.645)
>>> a
'2.65'
>>> a = int(2.5)
>>> a
2
二、要求超過17位的精度分析
python默認的是17位小數的精度,但是這里有一個問題,就是當我們的計算需要使用更高的精度(超過17位小數)的時候該怎麼做呢?
1. 使用格式化(不推薦)
>>> a = "%.30f" % (1/3)
>>> a
'0.'
可以顯示,但是不準確,後面的數字往往沒有意義。
2. 高精度使用decimal模塊,配合getcontext
>>> from decimal import *
>>> print(getcontext())
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero,
Overflow])
>>> getcontext().prec = 50
>>> b = Decimal(1)/Decimal(3)
>>> b
Decimal('0.')
>>> c = Decimal(1)/Decimal(17)
>>> c
Decimal('0.')
>>> float(c)
0.058823529411764705
默認的context的精度是28位,可以設置為50位甚至更高,都可以。這樣在分析復雜的浮點數的時候,可以有更高的自己可以控制的精度。其實可以留意下context裡面的這rounding=ROUND_HALF_EVEN
參數。ROUND_HALF_EVEN, 當half的時候,靠近even.
三、關於小數和取整
既然說到小數,就必然要說到整數。一般取整會用到這些函數:
1. round()
這個不說了,前面已經講過了。一定要注意它不是簡單的四捨五入,而是ROUND_HALF_EVEN的策略。
2. math模塊的ceil(x)
取大於或者等於x的最小整數。
3. math模塊的floor(x)
去小於或者等於x的最大整數。
>>> from math import ceil, floor
>>> round(2.5)
2
>>> ceil(2.5)
3
>>> floor(2.5)
2
>>> round(2.3)
2
>>> ceil(2.3)
3
>>> floor(2.3)
2
>>>
② python內置函數
python內置函數是什麼?一起來看下吧:
python內置函數有:
abs:求數值的絕對值
>>>abs(-2) 2
pmod:返回兩個數值的商和余數
>>>pmod(5,2) (2,1) >>pmod(5.5,2) (2.0,1.5)
bool:根據傳入的參數的邏輯值創建一個布爾值
>>>bool() #未傳入參數 False >>>bool(0) #數值0、空序列等值為False False >>>bool(1) True
all:判斷可迭代對象的每個元素是否都為True值
>>>all([1,2]) #列表中每個元素邏輯值均為True,返回True True >>> all(()) #空元組 True >>> all({}) #空字典 True
help:返回對象的幫助信息
>>> help(str) Help on class str in mole builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the 雹清object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) Return self+value.
_import_:動態導入模塊
index = __import__('index') index.sayHello()
locals:返回當前作用域內的局部變數和其值組成的字典
>>> def f(): print('before define a ') print(locals()) #作用域內無變數 a = 1 print('after define a') print(locals()) #作用域內有一個a變數,值為1 >>> f>>> f() before define a {} after 磨枝define a {'a': 1}
input:讀取用戶輸入值
>>瞎肆敏> s = input('please input your name:') please input your name:Ain >>> s 'Ain'
open:使用指定的模式和編碼打開文件,返迴文件讀寫對象
# t為文本讀寫,b為二進制讀寫 >>> a = open('test.txt','rt') >>> a.read() 'some text' >>> a.close()
eval:執行動態表達式求值
>>> eval('1+2+3+4') 10
除了上述舉例的函數之外,內置函數按分類還可分為:
1、數學運算(7個)
2、類型轉換(24個)
3、序列操作(8個)
4、對象操作(7個)
5、反射操作(8個)
6、變數操作(2個)
7、交互操作(2個)
8、文件操作(1個)
9、編譯操作(4個)
10、裝飾器(3個)
③ python float函數字元串轉換浮點數 保留位數
int函數能夠
(1)把符合數學格式的數字型字元串轉換成整數
(2)把浮點數轉換成整數,但是只是簡單的取整,而非四捨五入。
舉例:
1 aa = int("124") #Correct
2 print "aa = ", aa #result=124
3 bb = int(123.45) #correct
4 print "bb = ", bb #result=123
5 cc = int("-123.45") #Error,Can't Convert to int
6 print "cc = ",cc
7 dd = int("34a") #Error,Can't Convert to int
8 print "dd = ",dd
9 ee = int("12.3") #Error,Can't Convert to int
10 print ee
11
二、float函數將整數和字元串轉換成浮點數。
舉例:
1 aa = float("124") #Correct
2 print "aa = ", aa #result = 124.0
3 bb = float("123.45") #Correct
4 print "bb = ", bb #result = 123.45
5 cc = float(-123.6) #Correct
6 print "cc = ",cc #result = -123.6
7 dd = float("-123.34") #Correct
8 print "dd = ",dd #result = -123.34
9 ee = float('123v') #Error,Can't Convert to float
10 print ee
三、str函數將數字轉換成字元
舉例:
1 aa = str(123.4) #Correct
2 print aa #result = '123.4'
3 bb = str(-124.a) #SyntaxError: invalid syntax
4 print bb
5 cc = str("-123.45") #correct
6 print cc #result = '-123.45'
7 dd = str('ddd') #correct
8 print dd #result = ddd
9 ee = str(-124.3) #correct
10 print ee #result = -124.3
④ 【Python基礎】python基本語法規則有哪些
Python基本語法
Python的語法相對比C,C++,Java更加簡潔,比較符合人的正常思維。本篇介紹Python的基本語法,通過本篇文章你可以學到以下內容。
掌握Python的基本語法
識別Python中的關鍵字
Python是一門腳本語言,有以下特點:
面向對象:類
語法塊:使用縮進進行標記
注釋: #單行注釋,"""多行注釋""",'''我也是多行注釋''
列印與輸出:print(), input()
變數: 變數在賦值的時候確定變數的類型
模塊:通過import 模塊名進行載入模塊
Python的標識符
標識符是用戶編程時使用的名字,用於給變數、常量、函數、語句塊等命名,以建立起名稱與使用之間的關系。標識符通常由字母和數字以及其它字元構成。
標識符的命名遵循以下規定:
開頭以字母或者下劃線_,剩下的字元數字字母或者下劃線
Python遵循小駝峰命名法
不是使用Python中的關鍵字進行命名
代碼示例:
num = 10 # 這是一個int類型變數
錯誤命名示例:
123rate(數字開頭)、 mac book pro(含有空格),class(關鍵字)
Python關鍵字
以下列表中的關鍵字不可以當作標識符進行使用。Python語言的關鍵字只包含小寫字母。
⑤ Python如何轉換百分數字元串為浮點數
int函數能夠
(1)把符合數學格式的數字型字元串轉換成整數
(2)把浮點數轉換成整數,但是只是簡單的取整,而非四捨五入。
舉例:
1 aa = int("124") #Correct
2 print "aa = ", aa #result=124
3 bb = int(123.45) #correct
4 print "bb = ", bb #result=123
5 cc = int("-123.45") #Error,Can't Convert to int
6 print "cc = ",cc
7 dd = int("34a") #Error,Can't Convert to int
8 print "dd = ",dd
9 ee = int("12.3") #Error,Can't Convert to int
10 print ee
11
二、float函數將整數和字元串轉換成浮點數。
舉例:
1 aa = float("124") #Correct
2 print "aa = ", aa #result = 124.0
3 bb = float("123.45") #Correct
4 print "bb = ", bb #result = 123.45
5 cc = float(-123.6) #Correct
6 print "cc = ",cc #result = -123.6
7 dd = float("-123.34") #Correct
8 print "dd = ",dd #result = -123.34
9 ee = float('123v') #Error,Can't Convert to float
10 print ee
三、str函數將數字轉換成字元
舉例:
1 aa = str(123.4) #Correct
2 print aa #result = '123.4'
3 bb = str(-124.a) #SyntaxError: invalid syntax
4 print bb
5 cc = str("-123.45") #correct
6 print cc #result = '-123.45'
7 dd = str('ddd') #correct
8 print dd #result = ddd
9 ee = str(-124.3) #correct
10 print ee #result = -124.3
⑥ 怎麼將python時間段(Timedelta)轉化為int或float數值形式! 急。
1、打開visio studio 2015,在文件中打開新建項目,新建一個Python應用程序,並修改程序的名稱為int2date。
⑦ python中如何把string 轉換成int
用數字字元串初始化int類,就可以將整數字元串(str)轉換成整數(int):
In [1]: int(『1234』)
Out[1]: 1234
相反用整數初始化str類,就可以將整數(int)轉換為對應的字元串(str):
In [2]: str(1234)
Out[2]: 『1234』
如果字元串是浮點數,可以用字元串初始化float類,把浮點數字元串(str)轉換成浮點數(float):
In [3]: float(『12.34』)
Out[3]: 12.34
(7)floattointpython擴展閱讀:
Python (英國發音:/ˈpaɪθən/ 美國發音:/ˈpaɪθɑːn/), 是一種面向對象的解釋型計算機程序設計語言,由荷蘭人Guido van Rossum於1989年發明,第一個公開發行版發行於1991年。
Python是純粹的自由軟體,源代碼和解釋器CPython遵循 GPL(GNUGeneral Public License)許可。Python語法簡潔清晰,特色之一是強制用空白符(white space)作為語句縮進。
Python具有豐富和強大的庫。它常被昵稱為膠水語言,能夠把用其他語言製作的各種模塊(尤其是C/C++)很輕松地聯結在一起。常見的一種應用情形是,使用Python快速生成程序的原型(有時甚至是程序的最終界面),然後對其中有特別要求的部分,用更合適的語言改寫,比如3D游戲中的圖形渲染模塊,性能要求特別高,就可以用C/C++重寫,而後封裝為Python可以調用的擴展類庫。需要注意的是在您使用擴展類庫時可能需要考慮平台問題,某些可能不提供跨平台的實現。
7月20日,IEEE發布2017年編程語言排行榜:Python高居首位 。
2018年3月,該語言作者在郵件列表上宣布 Python 2.7將於2020年1月1日終止支持。用戶如果想要在這個日期之後繼續得到與Python 2.7有關的支持,則需要付費給商業供應商。