Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ var Builtins = []*Function{
return anyType, fmt.Errorf("invalid argument for abs (type %s)", args[0])
},
},
{
Name: "log2",
Fast: Log2,
Validate: func(args []reflect.Type) (reflect.Type, error) {
return validateRoundFunc("log2", args)
},
},
{
Name: "ceil",
Fast: Ceil,
Expand Down
4 changes: 4 additions & 0 deletions builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ func TestBuiltin(t *testing.T) {
{`abs(-5)`, 5},
{`abs(.5)`, .5},
{`abs(-.5)`, .5},
{`log2(8)`, 3.0},
{`log2(0.5)`, -1.0},
{`ceil(5.5)`, 6.0},
{`ceil(5)`, 5.0},
{`floor(5.5)`, 5.0},
Expand Down Expand Up @@ -253,6 +255,8 @@ func TestBuiltin_errors(t *testing.T) {
{`abs()`, `invalid number of arguments (expected 1, got 0)`},
{`abs(1, 2)`, `invalid number of arguments (expected 1, got 2)`},
{`abs("foo")`, `invalid argument for abs (type string)`},
{`log2()`, `invalid number of arguments (expected 1, got 0)`},
{`log2("foo")`, `invalid argument for log2 (type string)`},
{`int()`, `invalid number of arguments (expected 1, got 0)`},
{`int(1, 2)`, `invalid number of arguments (expected 1, got 2)`},
{`float()`, `invalid number of arguments (expected 1, got 0)`},
Expand Down
4 changes: 4 additions & 0 deletions builtin/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ func Abs(x any) any {
panic(fmt.Sprintf("invalid argument for abs (type %T)", x))
}

func Log2(x any) any {
return math.Log2(Float(x).(float64))
}

func Ceil(x any) any {
switch x := x.(type) {
case float32:
Expand Down
8 changes: 8 additions & 0 deletions docs/language-definition.md
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,14 @@ Returns the absolute value of a number.
abs(-5) == 5
```

### log2(n) {#log2}

Returns the binary logarithm of a number.

```expr
log2(8) == 3.0
```

### ceil(n) {#ceil}

Returns the least integer value greater than or equal to x.
Expand Down