top | item 23414872

Julia as a CLI Calculator

198 points| krjt | 5 years ago |krasjet.com | reply

130 comments

order
[+] dgb23|5 years ago|reply
This seems to be a very neat intro into Julia and a practical use case. I’ve been postponing to learn the language for a while now, but from what I heard/seen it seems to be extremely well designed.
[+] jweir|5 years ago|reply
I used it as my CLI calculator, just like the articles title. I used to use Ruby for this, but Julia is more concise but still readable. Concise enough I have written useful applications that can fit in a tweet.
[+] dunefox|5 years ago|reply
You should, it's a fun, useful language. It's starting to replace python for my use cases.
[+] enriquto|5 years ago|reply
I love the julia language. I would love to use julia as a command line calculator. Unfortunately, starting the interpreter is excruciatingly slow, an order of magnitude slower than octave or python (and several orders of magnitude slower than bc or dc).
[+] Sukera|5 years ago|reply
One way to alleviate the slowish startup is to use PackageCompiler.jl (discussed at the end of the article https://krasjet.com/rnd.wlk/julia/#packagecompiler.jl). I like that there's more than just the standard calculator operations available at the REPL, but I can see why you wouldn't use it if you don't need it and bc satisfies your needs.
[+] socialdemocrat|5 years ago|reply
How long does it take to start on your computer? If I have run it before. It takes less than 0.25 seconds. I use a several years old Mac. On none of my computers do I experience startup times which has any practical relevance to being productive.

The only real problem I have experienced in Julia is using plotting libraries and those you can include in your Julia image with PackageCompiler.

[+] eismcc|5 years ago|reply
Maybe a daemon model would be helpful here. REPL client could just boot instantly and forward operations to an already running Julia daemon
[+] dunefox|5 years ago|reply
Simply loading the REPL takes half a second for me. I use it all the time as a simple calculator.
[+] leephillips|5 years ago|reply
I suspect that the author starts the julia REPL up in the morning and leaves is running all day, so startup time would not be important.
[+] eigenspace|5 years ago|reply
Besides the other suggestions, you can do things like start julia using the --compile=min or -O0 command line flags to reduce / eliminate compilation overhead and make it startup quicker.

The beta version of version 1.5.0 starts up in 0.25 seconds with --compile=min and I believe it's the same on 1.4.0

[+] jaquers|5 years ago|reply
The typography in this post is beautiful (as well as the content), anybody know where this comes from? Did the author do it by hand or is it something off the shelf?

Asking for a friend...

[+] gen220|5 years ago|reply
I have a tangential question related to styling (and I agree the styling for this site is wonderful).

When designing your personal/corporate website/blog, how much weight do you attribute to users whose browsers refuse to load remote fonts (by preference or otherwise)?

I ask because I've noticed recently that some websites (notably, many google sites) are unusable, because they depend on remotely-loaded icons, which are replaced with unreadably-stretched alt-text with unintended form factors.

On this blog, for example, the default preformatted-font didn't seem to be monospaced, and the result is that the "julia" name is rendered incorrectly.

All this is meant to ask, do you ever test your designs with browser-default fonts? If not/so, is this conscious? Why?

To be clear, I intend for this to be a survey, not an inquisition. I'm trying to understand this trend better.

For my own answer. At my place of work, in spite of an avowed obsession with accessibility, our designs are regularly sabotaged by browser-default fonts and poorly-rendered alt-text.

[+] jaquers|5 years ago|reply
Here's the typeface https://typeof.net/Iosevka/

What struck me was the [ t a b ] stuff as well as the Latex reference, which looks to be embedded img in src, so there must be some sort of preprocessor?

[+] oefrha|5 years ago|reply
I use Mathematica as my advanced calculator. It’s a functional language with an extremely vast and consistent mathematical and non-mathematical library, top notch symbolic capabilities (SymPy is just child’s play in comparison), top notch numerical capabilities, and very decent performance. You certainly don’t need to write your own rotation function — well, 2D rotation is trivial, but what if you want 3D rotation around a vector? Mathematica’s got you covered. Got a command line mode too, see MathKernel.

The downside: it’s not free (as in beer or speech).

[+] ohsonice|5 years ago|reply
I've been using Julia as my CLI calculator for a few years now - cool to see this post! While teaching an online Linear Algebra class, I would use Julia to construct examples and quickly solve them. The syntax sugar of all the functional idioms make it very fun and easy to express more complicated ideas. This is a cool introduction- I was not aware (or had forgotten) about function chaining. Really curious about using more of Latexify as well :)

On an unrelated note, (as a mathematician) I have started using Maple a lot more as my analytic computational helper. Never really gave it the time of day in years past - it is quite powerful and intuitive. Funny note: I recently copied and pasted output of a Maple command into my Julia code and it was syntactically correct!

[+] knight17|5 years ago|reply
Since this is a calculator topic, I'd like request your input on which calculators you use.

I use the Emacs calculator (M-x calc) and XCalc (http://www.tordivel.no/xcalc/) as I like to use RPN calculators. The Windows 10 calculator is painful and slow. XCalc has a mini mode, where it will sit as a small, single line without distracting you too much. I like that feature very much.

One thing with Emacs is that I forget the shortcuts for non-frequent calculations that I'd have to go and search for it.

[+] majewsky|5 years ago|reply
My favorite calculator of all time is units(1). For example, to calculate how long it takes to download a 20 MiB file over a 56 kbit dialup connection:

  $ alias units='units --verbose' # in your shell rc
  $ units
  Currency exchange rates from FloatRates (USD base) on 2019-06-05
  3460 units, 109 prefixes, 109 nonlinear units
  
  You have: 56 kibibit/second
  You want: hour/20 mebibyte
          reciprocal conversion
          1 / (56 kibibit/second) = 0.8126984126984126977077949 hour/20 mebibyte
          1 / (56 kibibit/second) = (1 / 1.23046875) hour/20 mebibyte
Note that if you are on macOS, you want to install a more recent units via homebrew. The one shipping with the base system is positively ancient.
[+] scott_s|5 years ago|reply
Python repl in a newly opened terminal session. Which is similar to the posted submission.

During grad school, I went through a period of trying many different GUI based calculators, until I realized what I really wanted was a language's repl.

[+] knight17|5 years ago|reply
One good thing about the Emacs calculator is the sheer number of features available. I don't use many, but occasionally use the financial functions, and they are really great. Any suggestions on programs out there with financial functions?

See Andrew Hyatt's Emacs calculator for Financial calculation tutorial: http://web.archive.org/web/20171218022230/https://plus.googl...

(Link rot, Google Plus, web.archive.org!)

[+] drunkpotato|5 years ago|reply
I use insect almost daily ( https://github.com/sharkdp/insect ). It’s a command line calculator, not sure how well it would integrate with comint on emacs. Unit conversions built-in. I don’t know whether it has an RPN mode.

The other thing I do frequently is fire up a python3 repl for quick hits. I just did it yesterday for a complex mass file rename I couldn’t figure out how to do with shell variable replacement. With python it was easy with glob and os.rename.

[+] ibiza|5 years ago|reply
I use a function "ev" that wraps bc. It's crude, but handy:

    $ ev() { echo "scale=3; $*" | bc -l; }
    
    $ ev 22/7
    3.142
[+] oefrha|5 years ago|reply
I kid you not, I use Spotlight on macOS (cmd+space) as my simple calculator if I’m outside the terminal. If I’m inside the terminal I probably have an IPython instance open. For advanced stuff I use Mathematica as mentioned here: https://news.ycombinator.com/item?id=23428991
[+] bjoli|5 years ago|reply
I have all commands I don't remember bound to leader keys. When in calc I have [leader key] m and then which-key pops up everything I have stored.

Other than that, I use scratch in elisp mode and eval. Not as fluent as magnars, but this is a good example of what I mean (towards the end): https://youtu.be/jNa3axo40qM

[+] dTal|5 years ago|reply
Qalculate is the best desktop calculator I've used. It has a command line version, qalc.

Qalculate takes unit-aware calculation to the next level by including an algebraic solver. You don't have to rearrange everything to put your unknown on one side - you can just chuck 'x' into your equality somewhere and it'll work it out. For example, to verify the what-if xkcd assertion that an A10's main gun will propel Randall's car up to 7mph in 3 seconds:

(60/s) × (x s) × (395 grams) × (1010 m/s) = (3500 lbs)(70 mph) ≈ x = 2.0754319 s

2 seconds! Maybe Randall's car is heavier than 3500 lbs. How much heavier?

(60/s) × (3 s) × (395 grams) × (1010 m/s) = (x lb)(70 mph) ≈ x = 5059.1879

More like a Dodge Durango. Unless he's accounting for friction.

You see how nice it is to be able to swap around the unknowns in an equality. Other great features are a large number of built-in constants, an astounding variety of built-in functions - it's practically a CAS - and a command history, which is where I pulled the above example from. It also has a plugin for Plasma's krunner, so you can do quick calculations right there in the dropdown. To summarize: Qalculate is the shit.

[+] boogies|5 years ago|reply
Qalculate is great, but often I just use GNU bc. You just have to remember (or make some type of alias) to pass it the -l flag for floating point etc., and I also use -q for quiet. There's also dc(1) for RPN.
[+] benhurmarcel|5 years ago|reply
For an RPN calculator, I find orpie really great.

Otherwise I use WolframAlpha a lot.

[+] kps|5 years ago|reply
For simple quick things I use ksh $((expressions)).
[+] nsajko|5 years ago|reply
A problem with Julia is that it does not parse input numbers with arbitrary precision by default. Example:

  julia> sin(1.461920290375737576933544899379e+31)
  -0.9468766486679395

  julia> sin(parse(BigFloat, "1.461920290375737576933544899379e+31"))
  0.6864670207863400975666631018263839509022548965872940746039593018855528710432756
Fricas is better in this regard, some links:

https://en.wikipedia.org/wiki/FriCAS

https://fricas.github.io

https://github.com/fricas/fricas

http://www.euclideanspace.com/prog/scratchpad/fricas/

EDIT: some info about FriCAS: it's implementation is currently based on Common Lisp, on top of which a language called "Spad" (short for Scratchpad) is implemented. Fricas is a fork of the Axiom computer mathematics system, which in turn is a continuation of Scratchpad. EDIT: and, at least with SBCL, it can use GMP for bignum.

I only skimmed the article, but I believe Fricas supports all uses of Julia mentioned in the article, and more, like advanced symbolic integration.

[+] fsloth|5 years ago|reply
Oh, brilliant! This is exactly what I've been looking for. Didn't realize the syntax was so succint. So far I've preferred excel for my multidimensional calc needs but this fits my needs exactly (need to do simple back-of-the-envelope vector calculations time to time).
[+] RivieraKid|5 years ago|reply
I really wish there was a language based on Swift that would include most of the nice language, REPL and library characteristics of Julia (and perhaps few from Dart). That would get really close to a "perfect language" for me.

Overall I like Julia - and use it as a CLI calculator as well - but there are several things that prevent it from being a good general purpose language:

- OOP support is "meh".

- str.parse(Int).abs is more readable than abs(parse(Int, str)). And this is a very simple case, the readability difference is greater in more complex expressions.

- 1-based indexing.

- Lack of good support for nullability, think of "if let", "guard let", "??", "object?.property".

- There are some more, this is just from the top of my head.

EDIT: A better example of why Julia's syntax is less readable:

`images.first.resize(100, 100).crop(25, 25, 75, 75)`

versus

`crop(resize(first(images), 100, 100), 25, 25, 75, 75)`

[+] cycomanic|5 years ago|reply
One of my main gripes about matlab and that Julia unfortunately adopted is the dot syntax. Any other symbol would have worked, but the dot is just way too easy to overlook.

I think it is because it was initially developed for people primarily working with matrices.

Most of the things I do is actually based around multidimensional arrays so when I do operations I almost always want element-wise operations. Unfortunately you often don't even realise you do the wrong operation, just the result is wrong. So I have spend lots of time debugging, until I realised I had a missing dot somewhere, and then spending again significant time trying to find where the dot is missing.

I therefore always found the complaint about np.dot(x,y) being too verbose interesting, because I like that, it makes it explicit and is difficult to overlook.

[+] dklend122|5 years ago|reply
You can use the @. macro to dot an entire block.

I personally like the dot syntax. It's ergonomic, and provides cool stuff like this: https://julialang.org/blog/2017/01/moredots/

I don't know of an equivalent functionality in any other language.

[+] plashchynski|5 years ago|reply
I've been using Julia REPL as s scientific calculator for a few months. I'm impressed how wonderful it is. Thank you for the article!
[+] starpilot|5 years ago|reply
One thing I miss is RPN-string input. Unlike normal RPN where you load the "stack," for RPN string you can enter

> 2 3 + 4 *

as one line, press enter, and get 20. This lets you take advantage of the no-parens nature of RPN while viewing the expression on one line rather than flipping through the stack. Only Windows PowerToy scientific calculator had this mode, that I know of.

[+] CamTin|5 years ago|reply
this sounds like "dc" except with dc you'd need to add a "p" at the end to print the top of the stack
[+] cormullion|5 years ago|reply
This is a great article - interesting, well-written and beautifully presented!

A minor quibble in the typography - the use of small caps for every initial letter is slightly catching my eye every time I see it. Perhaps I don't see enough similar typography on the web to make it feel more natural ¯\\_(ツ)_/¯ ...

[+] krzyk|5 years ago|reply
I use python CLI for exactly the same :)
[+] DreamScatter|5 years ago|reply
Nice article! I'm the creator of the Grassmann.jl package, which was mentioned in the article :)
[+] seltzered_|5 years ago|reply
I wonder if it'd be possible to have a blend between this and https://calca.io where the repl output appears (and change dynamically) as specialized comments within a markdown-friendly format.
[+] rscho|5 years ago|reply
Julia is nice for scientific serious work, but for cli calc J (jsoftware.com) really rocks!
[+] 29athrowaway|5 years ago|reply
My personal choice for this is Jupyter and Sagemath.
[+] wbhart|5 years ago|reply
SageMath takes 3s to load for me (sometimes a lot more if my systems administrator has updated it recently, which seems to happen a lot).

I therefore use Pari/GP for my personal choice. I like the symbolic nature of Pari/GP over Sage or Julia, even though I spend nearly all of my life programming in Julia, and love the language a lot.

However, for computations of trivial things that I want to run really fast, I put them in a function in Julia (so that they are jit-compiled), since nothing will come close to that, by some orders of magnitude.

[+] dan-robertson|5 years ago|reply
My main calculator is gnu calc which is the calculator built into emails. It tends to hit various ceilings where it can’t go much further but it has lots of nice features:

1. The data I want to work with tends to be in my text editor so it makes sense to have the calculator there too. Macros can be used to fix up formatting to input numbers

2. Speed of input makes it so much nicer to use. If I look at the examples in the article, here is a comparison. Julia:

  7 / 4
  x = ans + 2 im 
  exp(x)
  A = [...]
  A * [...]
  [a^2 for a \in A]
Emacs:

  7 RET 4 /
  (0,2) + s t x (but I probably wouldn’t use a variable)
  s r x E (if I used the stack this is just “E”)
  [(same but RET or , not SPC)] s t A
  s r A [...] *
  s r A V M I Q (that’s vector map inverse square root)
These examples make emacs look bad because I’ve replicated saving things to variables it actually I’d just use the stack. I guess in Julia you can press the up arrow. There are other examples like 1 |> exp |> sin is just 1 E S in Calc (and those operations broadcast over vectors automatically, although I think emasculated does the right thing and doesn’t broadcast exp over matrices).

Skipping the massive tangent of non-calculator things about Julia, we move on to a discussion of plotting. There isn’t a Unicode-art plotting mode in emacs because we have had graphical terminals for over 30 years. In emacs you plot with g f and can then modify your plot with other commands. In just about every language you need to call a function called plot so you’re already losing on characters before you’ve even started. If plotting is fast and easy then exploration is easy.

3. The calculator has lots of useful features that fit well together. Plotting is built in. As are unit conversions, a bunch of symbolic algebra (simplification, differentiation, basic integration, curve fitting, solving equations, numeric integration/solutions, and a super nice facility for editing expressions). There’s a bunch of other functions for stats, vectors (both linalg and things like map/reduce), number theory, physics, etc. There are language modes for things like latex output too. Most stuff works on a bunch of number types (bigints, rationals, arbitrary precision floats, infinity, intervals thereof, complex numbers, error forms, symbolic expressions, dates)

4. I want to reiterate the point about speed. The thing I care about being fast is telling the computer what to do. It takes basically 0 time to do most mathematical operations so latency is dominated by input. So even though emacs uses interpreted emacs lisp and doesn’t even use hardware floating point numbers, it still feels faster than Julia with its optimising JIT. If I want to do something with a large amount of data then I can either wait a few seconds or realise that I’ve gone beyond calculator work and use something better suited.

I think Julia is a great language and it has great advantages over emacs for numerical computing. A big one is that the language and type system is much more naturally extensible for this sort of thing. But I don’t feel that it makes a particularly good calculator. The main reason to think that it is a good calculator is that the alternatives (bash/bc/python/matlab) are so bad.