【Python】PAT甲级 A1060:Are They Equal(科学计数法)
题目内容
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 10¹⁰⁰, 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:
题目要点
本题 25 分,是一道比较复杂的模拟题,既要考虑一些边界情况又要考虑浮点数带来的精度损失,因此处理起来异常棘手。
如果使用Python解这道题,强烈建议使用下面代码中标准库的 decimal 模块。因为题设中已知精确度范围在100以内,如果是小于1的小数,那么可能会精确到小数点百位,对于浮点数来说极易失去精度。如果直接使用输入的字符串类型数据分析,也会遇到麻烦。比如,输入数据可能是如0003.120
这样有前导零的不规范数字,还要先将不需要的零去掉。
经过测试,测试点3、5的数据就是需要严格精度的。因此,在做这道题时会出现一个诡异的情况,在通过网上收集的许多测试点后仍然无法完全通过PTA的测试。所以,使用 decimal 模块以定点数存储数据,并充分利用模块提供的一些方法可以极大地提高效率,直接针对问题的核心,避免陷入处理细枝末节的窘境。
源代码
额外测试点
本题有许多边界情况需要考虑,这里提供一些测试点以供参考。