Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining math functions in zsh?

Tags:

zsh

This is almost definitely a duplicate but I cant find a post with what I'm looking for.

I mainly use bash for work but I occasionally use zsh as a floating point calculator. While the zsh/mathfunc library is all well and good for sqrt, sin, etc., I wish to define other math functions within zsh, such as pow, such that they function thusly:

zsh% print $((pow(4.0, 4.0) + 1.0))
257.0

(Yes, I know about the built-in ** operator, this is just an example)

The closest I have gotten to this is to use something like print $(($(pow 4.0 4.0) + 1.0)) using functions as demonstrated by laviande22 but this is headache-inducing.

Note: I am not looking for an answer that gives the answer when the command is typed within bare zsh, such as zsh% pow 4 4. I am looking for a function that can be used within the math subsystem in the form given, i.e. zsh% print $((pow(4.0, 4.0))).

like image 629
guninvalid Avatar asked Oct 27 '25 05:10

guninvalid


1 Answers

functions -M mathfn could rescue. It defines a mathematical function, so we can use a arithmetic-style function calling expression such as mathfn(arg,...).

my-powi () {
  res=1
  for ((i=0; i<$2; i++))
    ((res = res * $1))
  return res
}

functions -M pow 2 2 my-powi

echo $((pow(4, 4) + 1))
# >> 257

Here is the zsh document:

functions -M [-s] mathfn [ min [ max [ shellfn ] ] ]
...
functions -M mathfn defines mathfn as the name of a mathematical function recognised in all forms of arithmetical expressions; see Arithmetic Evaluation. By default mathfn may take any number of comma-separated arguments. If min is given, it must have exactly min args; if min and max are both given, it must have at least min and at most max args. max may be -1 to indicate that there is no upper limit.
...
For example, the following prints the cube of 3:

zmath_cube() { (( $1 * $1 * $1 )) }
functions -M cube 1 1 zmath_cube
print $(( cube(3) ))

--- zshbuiltin(1), functions, Shell Bultin Commands

like image 83
hchbaw Avatar answered Oct 30 '25 09:10

hchbaw