Post Reply 
bc (basic calculator) and libraries of functions
02-09-2018, 03:10 PM (This post was last modified: 02-09-2018 03:11 PM by pier4r.)
Post: #1
bc (basic calculator) and libraries of functions
Follow up of: http://www.hpmuseum.org/forum/thread-101...l#pid90844

In linux, bc is a neat program with arbitrary precision.
https://en.wikipedia.org/wiki/Bc_(programming_language)

The point is that although it seems quite powerful for a possible math programming environment, to my knowledge there is no extensive library of math functions.
https://www.gnu.org/software/bc/manual/h...no/bc.html

Functions:
Quote: If bc is invoked with the -l option, a math library is preloaded and the default scale is set to 20. The math functions will calculate their results to the scale set at the time of their call. The math library defines the following functions:

s (x)
The sine of x, x is in radians.
c (x)
The cosine of x, x is in radians.
a (x)
The arctangent of x, arctangent returns radians.
l (x)
The natural logarithm of x.
e (x)
The exponential function of raising e to the value x.
j (n,x)
The bessel function of integer order n of x.

To my little knowledge the best that I found is the following:
http://phodd.net/gnu-bc/
and then
http://phodd.net/gnu-bc/bcfaq.html

it is a nice project in itself to try to make a library module for bc (that I think it will be worth it. Another fun todo).

Anyway, do you know any better collection (or libraries or repositories) of functions for bc? For example a file with many functions inside?

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
02-09-2018, 03:21 PM
Post: #2
RE: bc (basic calculator) and libraries of functions
Hello!

I vaguely remember "bc" from my unix days (ca. 1989-2000). BTW: Not only Linux has one on board, but every Macintosh running OS X as well.

In one of your linked articles I instantly found this droll piece of explanation:
"bc was preceded by dc, an earlier arbitrary-precision calculator written by the same authors. dc could do arbitrary-precision calculations, but its reverse Polish notation (RPN) syntax was inconvenient for users".

Saluti
Max
Find all posts by this user
Quote this message in a reply
02-10-2018, 03:01 AM
Post: #3
RE: bc (basic calculator) and libraries of functions
(02-09-2018 03:10 PM)pier4r Wrote:  Follow up of: http://www.hpmuseum.org/forum/thread-101...l#pid90844

In linux, bc is a neat program with arbitrary precision.
https://en.wikipedia.org/wiki/Bc_(programming_language)

bc is also available for Windows:

http://gnuwin32.sourceforge.net/packages/bc.htm

Does anyone know if there is a way to save and load files from the interactive mode? Right now, I'm pasting text into the bc window.

Tom L
Cui bono?
Find all posts by this user
Quote this message in a reply
02-10-2018, 09:39 AM (This post was last modified: 02-10-2018 09:42 AM by Massimo Gnerucci.)
Post: #4
RE: bc (basic calculator) and libraries of functions
(02-10-2018 03:01 AM)toml_12953 Wrote:  
(02-09-2018 03:10 PM)pier4r Wrote:  Follow up of: http://www.hpmuseum.org/forum/thread-101...l#pid90844

In linux, bc is a neat program with arbitrary precision.
https://en.wikipedia.org/wiki/Bc_(programming_language)

bc is also available for Windows:

http://gnuwin32.sourceforge.net/packages/bc.htm

Of course it is; yesterday I used the 1.07 version (bc + dc) available here.

(02-10-2018 03:01 AM)toml_12953 Wrote:  Does anyone know if there is a way to save and load files from the interactive mode? Right now, I'm pasting text into the bc window.

I could not find a way from the interactive mode either.

Greetings,
    Massimo

-+×÷ ↔ left is right and right is wrong
Visit this user's website Find all posts by this user
Quote this message in a reply
02-10-2018, 10:15 AM
Post: #5
RE: bc (basic calculator) and libraries of functions
(02-10-2018 09:39 AM)Massimo Gnerucci Wrote:  
(02-10-2018 03:01 AM)toml_12953 Wrote:  bc is also available for Windows:

http://gnuwin32.sourceforge.net/packages/bc.htm

Of course it is; yesterday I used the 1.07 version (bc + dc) available here.

Thanks for the tip on the newer version! The site I mentioned has great docs for 1.06 included in the file so it's worth it to me to use those with the newer bc from your site. 1.06 doesn't seem too different from 1.07.1 so most of the information applies. I do notice the transcendental functions s(x), c(x), a(x), etc. are much faster in 1.07.

Tom L
Cui bono?
Find all posts by this user
Quote this message in a reply
06-18-2018, 10:00 AM
Post: #6
RE: bc (basic calculator) and libraries of functions
I like to benchmark any new Linux server I come across with:

> time echo "scale=5000; 4*a(1)" | bc -l -q

3.141592653589793238462643383279502884197169399375105820974944592307\
81640628620899862803482534211706798214808651328230664709384460955058\
22317253594081284811174502841027019385211055596446229489549303819644\
28810975665933446128475648233786783165271201909145648566923460348610\
45432664821339360726024914127372458700660631558817488152092096282925\
40917153643678925903600113305305488204665213841469519415116094330572\
70365759591953092186117381932611793105118548074462379962749567351885\
75272489122793818301194912983367336244065664308602139494639522473719\
07021798609437027705392171762931767523846748184676694051320005681271\
45263560827785771342757789609173637178721468440901224953430146549585\
37105079227968925892354201995611212902196086403441815981362977477130\
99605187072113499999983729780499510597317328160963185950244594553469\
08302642522308253344685035261931188171010003137838752886587533208381\
42061717766914730359825349042875546873115956286388235378759375195778\
18577805321712268066130019278766111959092164201989380952572010654858\
63278865936153381827968230301952035301852968995773622599413891249721\
77528347913151557485724245415069595082953311686172785588907509838175\
46374649393192550604009277016711390098488240128583616035637076601047\
10181942955596198946767837449448255379774726847104047534646208046684\
25906949129331367702898915210475216205696602405803815019351125338243\
00355876402474964732639141992726042699227967823547816360093417216412\
19924586315030286182974555706749838505494588586926995690927210797509\
30295532116534498720275596023648066549911988183479775356636980742654\
25278625518184175746728909777727938000816470600161452491921732172147\
72350141441973568548161361157352552133475741849468438523323907394143\
33454776241686251898356948556209921922218427255025425688767179049460\
16534668049886272327917860857843838279679766814541009538837863609506\
80064225125205117392984896084128488626945604241965285022210661186306\
74427862203919494504712371378696095636437191728746776465757396241389\
08658326459958133904780275900994657640789512694683983525957098258226\
20522489407726719478268482601476990902640136394437455305068203496252\
45174939965143142980919065925093722169646151570985838741059788595977\
29754989301617539284681382686838689427741559918559252459539594310499\
72524680845987273644695848653836736222626099124608051243884390451244\
13654976278079771569143599770012961608944169486855584840635342207222\
58284886481584560285060168427394522674676788952521385225499546667278\
23986456596116354886230577456498035593634568174324112515076069479451\
09659609402522887971089314566913686722874894056010150330861792868092\
08747609178249385890097149096759852613655497818931297848216829989487\
22658804857564014270477555132379641451523746234364542858444795265867\
82105114135473573952311342716610213596953623144295248493718711014576\
54035902799344037420073105785390621983874478084784896833214457138687\
51943506430218453191048481005370614680674919278191197939952061419663\
42875444064374512371819217999839101591956181467514269123974894090718\
64942319615679452080951465502252316038819301420937621378559566389377\
87083039069792077346722182562599661501421503068038447734549202605414\
66592520149744285073251866600213243408819071048633173464965145390579\
62685610055081066587969981635747363840525714591028970641401109712062\
80439039759515677157700420337869936007230558763176359421873125147120\
53292819182618612586732157919841484882916447060957527069572209175671\
16722910981690915280173506712748583222871835209353965725121083579151\
36988209144421006751033467110314126711136990865851639831501970165151\
16851714376576183515565088490998985998238734552833163550764791853589\
32261854896321329330898570642046752590709154814165498594616371802709\
81994309924488957571282890592323326097299712084433573265489382391193\
25974636673058360414281388303203824903758985243744170291327656180937\
73444030707469211201913020330380197621101100449293215160842444859637\
66983895228684783123552658213144957685726243344189303968642624341077\
32269780280731891544110104468232527162010526522721116603966655730925\
47110557853763466820653109896526918620564769312570586356620185581007\
29360659876486117910453348850346113657686753249441668039626579787718\
55608455296541266540853061434443185867697514566140680070023787765913\
44017127494704205622305389945613140711270004078547332699390814546646\
45880797270826683063432858785698305235808933065757406795457163775254\
20211495576158140025012622859413021647155097925923099079654737612551\
76567513575178296664547791745011299614890304639947132962107340437518\
95735961458901938971311179042978285647503203198691514028708085990480\
10941214722131794764777262241425485454033215718530614228813758504306\
33217518297986622371721591607716692547487389866549494501146540628433\
66393790039769265672146385306736096571209180763832716641627488880078\
69256029022847210403172118608204190004229661711963779213375751149595\
01566049631862947265473642523081770367515906735023507283540567040386\
74351362222477158915049530984448933309634087807693259939780541934144\
73774418426312986080998886874132604720

real 1m58.887s
user 1m58.782s
sys 0m0.016s

That's when running on a CubieTruck 3 with Debian Stretch.
Find all posts by this user
Quote this message in a reply
06-18-2018, 02:15 PM (This post was last modified: 06-19-2018 08:44 AM by Luigi Vampa.)
Post: #7
RE: bc (basic calculator) and libraries of functions
I do enjoy programming in BASH, when you need a glue language.
I found this link (in Spanish) useful.

EDIT on 20180620: URL changed to the original web page of the author.

Saludos Saluti Cordialement Cumprimentos MfG BR + + + + +
Luigi Vampa +
Free42 '<3' I + +
Find all posts by this user
Quote this message in a reply
07-06-2018, 12:08 AM
Post: #8
RE: bc (basic calculator) and libraries of functions
bc number theory programs:
http://www.numbertheory.org/gnubc/gnubc.html

Keith own arbitrary precision calculator:
http://www.numbertheory.org/calc/krm_calc.html
Find all posts by this user
Quote this message in a reply
07-11-2018, 11:37 AM
Post: #9
RE: bc (basic calculator) and libraries of functions
Thanks for sharing!

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
07-21-2018, 08:40 PM (This post was last modified: 07-21-2018 08:43 PM by pier4r.)
Post: #10
RE: bc (basic calculator) and libraries of functions
I was contemplating one aspect that stops me to use this or that well-known programming language. The fact that my homelab has all the different types of OSes and therefore it is a bit difficult to have the programming language of choice on the minimum needed versions over all systems.

The languages that is the most stable of all, being still relatively simple to use, is gawk. Its lack of math (many) functions, though, pushed me to think multiple times to combine it with bc (in the two way IO process, that is pretty handy https://www.gnu.org/software/gawk/manual...002fO.html ). Bc does the function computation, the rest is done by awk. Is not optimal, but is handy.

Well today I noticed that since 4.1 awk just extended "for fun" the math abilities to arbitrary precision. https://www.gnu.org/software/gawk/manual...Arithmetic

I am pretty sure that someone shared already an extended math library on the now defuct awk.info site (n1), anyway porting the functions made for bc to gawk itself may make them even more handy for quick prototyping/scripting. It could be handy even for others.

n1: "the internet does not forget", well no. It forgets a lot. Another nice site to disappear in some days is: https://chessprogramming.wikispaces.com/ , although they are trying to move it to their own domain. The point being, without maintainer, things are lost.

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
07-21-2018, 11:30 PM (This post was last modified: 04-17-2020 12:14 PM by Albert Chan.)
Post: #11
RE: bc (basic calculator) and libraries of functions
For trying things out, unlike bc, gawk lack a REPL

I made a simple REPL for gawk, for trying things out.
Code:
# igawk.py
import sys
from subprocess import Popen, PIPE

class UserInput:
    def __init__(self, inp):
        self.inp = inp
        self.output_chars = [0,0]

class Runner:
    def __init__(self, name, args):
        self.user_input = []
        self.compile_error = ""
        self.input_num = 0
        self.prog = name + args
        self.prompt = name + ":%d> "
        self.output_chars = [0,0]
        
    def read_line(self):
        while 1:
            prompt = self.prompt
            if prompt: prompt = prompt % (self.input_num + 1)
            line = raw_input(prompt)
            if line == '\\': line = '\t'.join(sys.stdin.readlines())
            line = line.strip()
            if line: return line

    def do_run(self):
        while 1:
            line = self.read_line()
            type = dot_cmd_process(self, line)
            if type is None: continue   # DOT cmd processed

            if type == 'INPUT':         # add line + run_awk
                if line[0] == '=':      # shorthand for print ...
                    line = 'print ' + line[1:]
                line += ')' * (line.count('(') - line.count(')'))
                last = UserInput(line)
                try:   self.user_input[self.input_num] = last
                except IndexError: self.user_input.append(last)
                self.input_num += 1
            else:
                last = self.user_input[self.input_num - 1]

            run = Popen(self.prog, stdin=PIPE, stdout=PIPE, stderr=PIPE)
            outputs = run.communicate(self.get_source())

            if run.returncode:
                self.compile_error = '\n'.join(outputs)
                print "[Compile error - type .e to see it.]"
                dot_u(self)
                continue

            for i, output in enumerate(outputs):
                n = len(output) - self.output_chars[i]
                if not n: continue
                last.output_chars[i] = n
                self.output_chars[i] += n
                print output[-n:]

    def get_user_input(self):
        return self.user_input[:self.input_num]

    def get_source(self):
        code = [ line.inp for line in self.get_user_input() ]
        return 'BEGIN {\n%s\n}' % ';\n'.join(code)

def dot_q(runner): raise EOFError()
def dot_e(runner): print runner.compile_error

def dot_l(runner, i=0):
    for line in runner.get_user_input():
        i = i+1
        print "%d\t%s" % (i, line.inp)

def dot_r(runner):
    n = runner.input_num
    if n < len(runner.user_input):
        runner.input_num = n + 1
        redo = runner.user_input[n]
        print "[Redo '%s'.]" % redo.inp
        return redo     # execute command again!
    else:
        print "[Nothing to redo.]"

def dot_u(runner):
    n = runner.input_num
    if n:
        runner.input_num = n = n - 1
        undone = runner.user_input[n]
        runner.output_chars[0] -= undone.output_chars[0]
        runner.output_chars[1] -= undone.output_chars[1]
        print "[Undone '%s'.]" % undone.inp
    else:
        print "[Nothing to undo.]"

def dot_U(runner):
    runner.compile_error = ""
    runner.input_num = 0
    runner.output_chars = [0,0]
    print "[Undo ALL]"

def dot_h(runner):
    for cmd in sorted(dot_cmds, key=str.lower):
        print cmd, dot_cmds[cmd][0]

def dot_cmd_process(runner, inp):
    if inp not in dot_cmds: return 'INPUT'
    return dot_cmds[inp][1]( runner )

dot_cmds = {
    ".h" : ( "Show this help message", dot_h ),
    ".q" : ( "Quit", dot_q ),
    ".e" : ( "Show the last compile errors/warnings", dot_e ),
    ".l" : ( "List the code you have entered", dot_l ),
    ".r" : ( "Redo undone command", dot_r ),
    ".u" : ( "Undo previous command", dot_u ),
    ".U" : ( "Undo all commands", dot_U),
    }

if __name__ == '__main__':
    prog = 'gawk' if len(sys.argv)==1 else sys.argv[1]
    args = ' -vOFMT="%.17g" -vORS="" -f -'
    
    if   prog == 'perl': args = ' -'
    elif prog == 'awk' : pass           # NOTE: 53-bits rounding
    elif prog != 'gawk': prog = None    # Force TypeError
    
    try: Runner(prog, args).do_run()
    except EOFError: pass               # Ctrl-Z to exit
    except TypeError: print "Usage: igawk.py [perl | awk | gawk]"

Example, below trick returns base^(-precision), both decimal and binary system

> igawk.py
gawk:1> x = 1/3
gawk:2> = 1-x-x-x
1.1102230246251565e-016
Find all posts by this user
Quote this message in a reply
07-22-2018, 10:22 AM
Post: #12
RE: bc (basic calculator) and libraries of functions
For those that are puzzled about REPL (like me): https://en.wikipedia.org/wiki/Read%E2%80...print_loop

In my case when I need interactivity I use bc (or something with continuous memory like the nq41 or the like). Normally if gawk is there, bc is there too.

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
07-22-2018, 01:34 PM
Post: #13
RE: bc (basic calculator) and libraries of functions
Those familiar with RPL might use the GNU Emacs Calculator.
Within emacs you can start it with:
M-x calc

HTH
Thomas
Find all posts by this user
Quote this message in a reply
08-27-2018, 11:57 AM
Post: #14
RE: bc (basic calculator) and libraries of functions
Today while testing some powers I realized that the powr operator is a bit strict.

"The result of the expression is the value of the first raised to the second. The second expression must be an integer."

Bummer. Exp(ln(x)) to the rescue

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
08-27-2018, 02:28 PM
Post: #15
RE: bc (basic calculator) and libraries of functions
more surprises with bc: https://www.johndcook.com/blog/2010/07/1...h-library/

Not only is the exponent must be integer, unary minus had precedence above ^

- 3 ^ 2 => 9
- - - - 3 ^ 2 => 9

On some old bc version x=-y and x= -y had different meanings ... weird

see page 6 of http://www.unixprogram.com/bc.pdf
Find all posts by this user
Quote this message in a reply
08-27-2018, 07:18 PM (This post was last modified: 09-02-2018 08:29 AM by pier4r.)
Post: #16
RE: bc (basic calculator) and libraries of functions
Nice article. Bc -l on Twitter is a nice idea too. To emulate!

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
10-22-2018, 09:02 AM
Post: #17
RE: bc (basic calculator) and libraries of functions
slightly related to bc, although for statistics is better.
https://www.mankier.com/1/datamash

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
10-22-2018, 06:01 PM (This post was last modified: 10-22-2018 06:04 PM by Luigi Vampa.)
Post: #18
RE: bc (basic calculator) and libraries of functions
(10-22-2018 09:02 AM)pier4r Wrote:  slightly related to bc, although for statistics is better.
https://www.mankier.com/1/datamash

It might be useful.
Really interesting!
Thanks for sharing, pier4r!!

EDIT: this seems to be the GNU project page
https://www.gnu.org/software/datamash/

Saludos Saluti Cordialement Cumprimentos MfG BR + + + + +
Luigi Vampa +
Free42 '<3' I + +
Find all posts by this user
Quote this message in a reply
10-24-2018, 03:30 PM
Post: #19
RE: bc (basic calculator) and libraries of functions
(10-22-2018 06:01 PM)Luigi Vampa Wrote:  EDIT: this seems to be the GNU project page
https://www.gnu.org/software/datamash/

yes but the gnu page has an older manual.

Wikis are great, Contribute :)
Find all posts by this user
Quote this message in a reply
10-28-2018, 05:52 AM
Post: #20
RE: bc (basic calculator) and libraries of functions
(07-21-2018 08:40 PM)pier4r Wrote:  n1: "the internet does not forget", well no. It forgets a lot. Another nice site to disappear in some days is: https://chessprogramming.wikispaces.com/ , although they are trying to move it to their own domain. The point being, without maintainer, things are lost.

The Internet may forget, but Archive.org still remembers both sites.
Find all posts by this user
Quote this message in a reply
Post Reply 




User(s) browsing this thread: 6 Guest(s)