32

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
EhevuTov
  • 20,205
  • 16
  • 66
  • 71

1 Answers1

55
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
$
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 20
    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). – jwodder Apr 25 '12 at 21:40
  • 4
    You answered that very well in 1min. You're an SO demigod. – EhevuTov Apr 25 '12 at 21:40
  • @EhevuTov Pure luck; I happened on the question moments after you posted it, and knew the answer. – Jonathan Leffler Apr 25 '12 at 21:41
  • 2
    @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). – Jonathan Leffler Apr 25 '12 at 21:44
  • 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.) – Jonathan Leffler Apr 09 '20 at 06:17
  • 1
    @JonathanLeffler You may need some math papers instead of Unix utility. Keywords: Repeating decimal, repetend length. – Weekend May 27 '21 at 06:27