Difference between printf% .3f and bc

So this is a hackerrank problem ( https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations ). Basically, input is an arithmetic expression, and I have to print out a formatted answer (3 decimal places). I tried it first

read exp echo "scale = 3; $exp" | bc -l 

He passed several tests, but not the first.

5+50*3/20 + (19*2)/7 17.929 5+50*3/20 + (19*2)/7 answer is 17.929 , but my code outputs 17.928 . I tried this code instead

 read exp printf "%.3f\n" `echo $exp | bc -l` 

Note: the echo part should be in the opposite direction, but I put `` so as not to be confused with the quotation marks of the block. All tests passed. So what's the difference?

+5
source share
4 answers

The reason these two are different from each other is because bc always truncates numbers, not rounds them. I. e. echo "scale = 3 ; 8/9" | bc echo "scale = 3 ; 8/9" | bc produces 0.888 instead of correctly rounded 0.889.

Your test case is evaluated to 17.928571429, which is rounded to 17.929 with your printf approach, but disconnected to 17.928 using the bc approach.

+5
source

I think the problem is scale = 3; part. For example, if you use

  printf "%.3f\n" ` echo "scale = 3 ; $exp " | bc -l` 

You will again receive 17.928. Therefore, the answer: you need to set the scale to at least 4, and then print it in a three-digit format.

+2
source

The problem is the rounding and / or significant digits returned by bc . When you use echo with scale=3 , you rely on bc to return only 3 digits. When you tell printf to output only 3 decimal places (using the %.3f format), you rely on printf to determine which digits. Essentially, the difference is rounding done with bc using scale=3 and done by printf with double conversion %.3f .

+1
source
 v=$(sed 's/[[:blank:]]//g') (echo "scale=4"; echo $v) | bc | xargs printf '%.3f' 

The above reads an integer from stdin, deletes blank lines, passes it to bc to perform the calculation with an accuracy of 4 digits, and then formats it with the correct rounding to 3 digits using printf. My solution to the aforementioned HackerRank problem.

0
source

Source: https://habr.com/ru/post/1203896/


All Articles