[SOLVED] BC provides incorrect decimal results, but only on the last two decimal places...
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
BC provides incorrect decimal results, but only on the last two decimal places...
Running RHEL 5.3 on a 2.6.18-128.el5 kernel. It's a VM.
bc v1.06
bash v3.2.25((1)-release (x86-64-redhat-linux-gnu)
My specific issue is getting bc to properly show decimals. I have a program that receives arbitrary numbers and then does percentage calculations based on what it gets - it is never correct, and troubleshooting bc has lead me to these conclusions:
If I do: echo "scale=2; (1/3)*100" | bc -l
I get: 33.00 (obviously incorrect)
If I do: echo "scale=2; (1/3)*101" | bc -l
I get: 33.33 (given rounding, this is close enough)
If I do: echo "scale=4; (1/3)*100" | bc -l
I get: 33.3300 (obviously incorrect, but it is interesting that bc chose to make the first two decimals correct)
I have tried using the -l option, not using the -l option, providing artificial decimal places for all constants in the equation (just in case bc likes to drop decimals when the input doesn't have them) and so on. I've swapped in printf for echo, and manually run the bc program without piping input. bc is consistently wrong in all cases where I use "100" as the multiplier.
It's probably just order of operations and your scale=4. 1/3 is being computed as .3333 (only four decimal places since scale=4), then when multiplied by 100 you get 33.3300. If you do 100*1/3 it does the 100*1 first, giving you 100.0000, then divides that by 3 giving you the full precision 33.3333.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.