fix(tools): calculator reads each written number from its text
The float ast had already rounded each literal, so ceil(1.0000000000000001) gave 1, 1e-400/1e-400 was refused as a division by zero and 1e400-1e400 as out of range. Float literals are now read from the expression text with Decimal (written numbers past 1e4000 are refused unparsed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ math functions and fractional powers work in floats.
|
||||
import ast
|
||||
import math
|
||||
import operator
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from fractions import Fraction
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
@@ -19,6 +20,8 @@ from ..types import ToolExecutionResult
|
||||
MAX_EXPRESSION_CHARS = 200
|
||||
# Largest exact power worked out (about 3000 digits); bigger ones are refused.
|
||||
_MAX_POWER_BITS = 10_000
|
||||
# Largest power of ten a written number may carry (1e4000); bigger ones are refused unparsed.
|
||||
_MAX_LITERAL_EXPONENT = 4000
|
||||
|
||||
_BINARY = {
|
||||
ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
|
||||
@@ -52,21 +55,34 @@ def _power(base, exponent):
|
||||
return result
|
||||
|
||||
|
||||
def _eval(node):
|
||||
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
|
||||
# As written: the float 1.1 becomes 11/10, not the binary 1.100000000000000088...
|
||||
def _number(node, text):
|
||||
if type(node.value) is int:
|
||||
return Fraction(node.value)
|
||||
# A float as written in the expression, not the float ast already rounded it to: 1.1 is 11/10,
|
||||
# 1.0000000000000001 stays above 1, and 1e-400 is not 0.
|
||||
try:
|
||||
written = Decimal(ast.get_source_segment(text, node) or "")
|
||||
except InvalidOperation:
|
||||
return Fraction(repr(node.value))
|
||||
if not written.is_finite() or abs(written.adjusted()) > _MAX_LITERAL_EXPONENT:
|
||||
raise _Refused("a number has too many digits")
|
||||
return Fraction(written)
|
||||
|
||||
|
||||
def _eval(node, text):
|
||||
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
|
||||
return _number(node, text)
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
|
||||
return _power(_eval(node.left), _eval(node.right))
|
||||
return _power(_eval(node.left, text), _eval(node.right, text))
|
||||
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
|
||||
return _BINARY[type(node.op)](_eval(node.left), _eval(node.right))
|
||||
return _BINARY[type(node.op)](_eval(node.left, text), _eval(node.right, text))
|
||||
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
|
||||
return _UNARY[type(node.op)](_eval(node.operand))
|
||||
return _UNARY[type(node.op)](_eval(node.operand, text))
|
||||
if isinstance(node, ast.Name) and node.id in _CONSTANTS:
|
||||
return _CONSTANTS[node.id]
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCTIONS
|
||||
and not node.keywords):
|
||||
return _FUNCTIONS[node.func.id](*[_eval(a) for a in node.args])
|
||||
return _FUNCTIONS[node.func.id](*[_eval(a, text) for a in node.args])
|
||||
raise _Refused("only numbers, + - * / ^ %, parentheses, "
|
||||
+ ", ".join([*_FUNCTIONS, *_CONSTANTS]) + " are allowed")
|
||||
|
||||
@@ -99,7 +115,7 @@ def calculate(expression: str) -> str:
|
||||
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
||||
raise _Refused("the expression is not valid math")
|
||||
try:
|
||||
return _readable(_eval(tree.body))
|
||||
return _readable(_eval(tree.body, text))
|
||||
except ZeroDivisionError:
|
||||
raise _Refused("it divides by zero")
|
||||
except OverflowError:
|
||||
|
||||
@@ -18,6 +18,9 @@ idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis,
|
||||
binary float), so `+ - * / // %` and whole-number powers have no rounding error: `ceil(1.1*100)`
|
||||
is 110 and `floor(0.3/0.1)` is 3. Only the math functions, `pi`, `e` and fractional powers work
|
||||
in floats.
|
||||
A number is read from its written text, so decimals longer than 17 digits and exponents beyond
|
||||
the float range stay as written too (`ceil(1.0000000000000001)` is 2, `1e-400/1e-400` is 1); a
|
||||
written number past 1e4000 (or below 1e-4000) is refused.
|
||||
- **Signs people write.** `^` is a power, `×` multiplies, `÷` divides, `−` is a minus.
|
||||
- **Raw data.** No LLM call. The answer is `<expression as given> = <value>`: whole numbers exact,
|
||||
a float that is a whole number below 10^15 as that whole number, other values to 10 significant
|
||||
|
||||
Reference in New Issue
Block a user