How to get a decimal number when dividing in bc?
Asked Answered
L

1

33

I need 'bc' to divide a number and give me not only the floor but also the remainder. For instance 'bc' gives me '2' if I do '5/2'. I'd really want something like '2.5'

Maybe this isn't even possible?

Lucite answered 25/4, 2012 at 21:35 Comment(0)
D
58
scale = 20

It sets the number of decimal places.

$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
355/113
3
scale=20
355/113
3.14159292035398230088
quit
$
Derivative answered 25/4, 2012 at 21:37 Comment(6)
Also note that you can avoid manually setting scale every time you use bc by invoking it with the -l option (which automatically sets scale to 20 and also defines several math functions).Vida
You answered that very well in 1min. You're an SO demigod.Lucite
@Lucite Pure luck; I happened on the question moments after you posted it, and knew the answer.Derivative
@jwodder: Thanks! I knew about the -l option (which I forever think should be -m for 'maths library', but that's my problem); I hadn't noticed the automatic setting of scale. If you invoke bc -l, you can write: 4*a(1) and get 3.14159265358979323844, a better approximation to π than 355/113 (though that is good to 6 dp, which is good enough for many purposes).Derivative
If you're easily amused (or bored while "social distancing"), then 355/113 does have a repeating pattern of digits in the decimal expansion, but the pattern is 112 digits long, starting at the 141 after the decimal point. Set scale = 350 (or 355?), and you'll find the repeating pattern is 1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168. (Is there a standard Unix utility that finds the repeat without programming? I don't know of one.)Derivative
@JonathanLeffler You may need some math papers instead of Unix utility. Keywords: Repeating decimal, repetend length.Institutor

© 2022 - 2024 — McMap. All rights reserved.