Powers and remainders in the calculator (closes #3)
check / check (push) Successful in 57s

internal/calc gets its own tokenizer and precedence-climbing parser in
place of go/parser, which cannot express a power operator; go/constant
still computes. ^ (also **) binds tighter than * / % and a sign on its
left, and groups to the right. % takes the sign of the divisor and is
exact on decimals. A whole exponent is computed exactly while the
result's numerator and denominator stay within 4096 bits; otherwise,
and for a fractional exponent, in float64. A remainder, or the sign of
a negative base's power, that depends on a value go/constant holds
rounded is refused as too large. The welcome text and the replies
mention the new operators; a negative base with a fractional exponent
gets its own reply.

Model: opus-5-5
This commit is contained in:
clawbot
2026-09-29 00:08:26 +00:00
parent 09a5caa8ab
commit aeb040d156
7 changed files with 522 additions and 96 deletions
+5 -3
View File
@@ -22,7 +22,7 @@ import (
const DisplayName = "calc"
// Welcome is sent to everyone whose contact request the bot accepts.
const Welcome = "Send me arithmetic, such as 2 + 2 or 5 * 5/2, " +
const Welcome = "Send me arithmetic, such as 2 + 2, 5 * 5/2, 2^10 or 7 % 3, " +
"and I will reply with the result."
const (
@@ -223,8 +223,10 @@ func Reply(text string) string {
return "I cannot divide by zero."
case errors.Is(err, calc.ErrTooLarge):
return "The result is too large for me."
case errors.Is(err, calc.ErrNoRealResult):
return "A negative number to a fractional power has no real result."
default:
return "I only understand arithmetic: numbers, + - * / and " +
"parentheses, such as 5 * 5/2."
return "I only understand arithmetic: numbers, + - * /, ^ for a power, " +
"% for a remainder, and parentheses, such as 5 * 5/2 or 2^10."
}
}
+6 -3
View File
@@ -16,6 +16,8 @@ func TestReply(t *testing.T) {
for in, want := range map[string]string{
"2 + 2": "4",
"5 * 5/2": "12.5",
"2^10": "1024",
"7 % 3": "1",
} {
if got := bot.Reply(in); got != want {
t.Errorf("Reply(%q) = %q, want %q", in, got, want)
@@ -23,9 +25,10 @@ func TestReply(t *testing.T) {
}
for in, want := range map[string]string{
"hello": "I only understand arithmetic",
"1 / 0": "I cannot divide by zero.",
"1e400": "The result is too large for me.",
"hello": "I only understand arithmetic",
"1 / 0": "I cannot divide by zero.",
"1e400": "The result is too large for me.",
"(-8)^0.5": "A negative number to a fractional power has no real",
strings.Repeat("1+", calc.MaxInputLength) + "1": "That is too long for me",
} {
if got := bot.Reply(in); !strings.HasPrefix(got, want) {