【Python】PAT甲級(jí) A1060:Are They Equal(科學(xué)計(jì)數(shù)法)
題目?jī)?nèi)容
If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123×10? with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine.
Input Specification:
Each input file contains one test case which gives three numbers?, ?and? , where?(<100) is the number of significant digits, and ?and ?are the two float numbers to be compared. Each float number is non-negative, no greater than 101??, and that its total digit number is less than 100.
Output Specification:
For each test case, print in a line YES
if the two numbers are treated equal, and then the number in the standard form 0.d[1]...d[N]*10^k
(d[1]
>0 unless the number is 0); or NO
if they are not treated equal, and then the two numbers in their standard form. All the terms must be separated by a space, with no extra space at the end of a line.
Note: Simple chopping is assumed without rounding.
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
題目要點(diǎn)
本題 25 分,是一道比較復(fù)雜的模擬題,既要考慮一些邊界情況又要考慮浮點(diǎn)數(shù)帶來的精度損失,因此處理起來異常棘手。
如果使用Python解這道題,強(qiáng)烈建議使用下面代碼中標(biāo)準(zhǔn)庫的 decimal 模塊。因?yàn)轭}設(shè)中已知精確度范圍在100以內(nèi),如果是小于1的小數(shù),那么可能會(huì)精確到小數(shù)點(diǎn)百位,對(duì)于浮點(diǎn)數(shù)來說極易失去精度。如果直接使用輸入的字符串類型數(shù)據(jù)分析,也會(huì)遇到麻煩。比如,輸入數(shù)據(jù)可能是如0003.120
這樣有前導(dǎo)零的不規(guī)范數(shù)字,還要先將不需要的零去掉。
經(jīng)過測(cè)試,測(cè)試點(diǎn)3、5的數(shù)據(jù)就是需要嚴(yán)格精度的。因此,在做這道題時(shí)會(huì)出現(xiàn)一個(gè)詭異的情況,在通過網(wǎng)上收集的許多測(cè)試點(diǎn)后仍然無法完全通過PTA的測(cè)試。所以,使用 decimal 模塊以定點(diǎn)數(shù)存儲(chǔ)數(shù)據(jù),并充分利用模塊提供的一些方法可以極大地提高效率,直接針對(duì)問題的核心,避免陷入處理細(xì)枝末節(jié)的窘境。
源代碼
額外測(cè)試點(diǎn)
本題有許多邊界情況需要考慮,這里提供一些測(cè)試點(diǎn)以供參考。