1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! Functions operate on the same typed values as binary arithmetic.
use super::{DisplayUnit, Parser, Value};
use crate::{Error, re};
use num_traits::Signed;
pub(in crate::plugins) fn has_function(input: &str) -> bool {
re!(r"\b(?:abs|min|max|mean|sum|square|sqrt|round|real|rational|sin|cos|tan)\(").is_match(input)
}
impl Parser<'_> {
pub(super) fn function(&mut self, input: &str, depth: usize) -> Option<Result<Value, Error>> {
let (name, tail) = input.split_once('(')?;
if !matches!(
name,
"abs"
| "min"
| "max"
| "mean"
| "sum"
| "square"
| "sqrt"
| "round"
| "real"
| "rational"
| "sin"
| "cos"
| "tan"
) {
return None;
}
if matches!(name, "real" | "rational" | "sin" | "cos" | "tan") && self.standard {
return None;
}
Some((|| {
let invalid = || Error("invalid_expression".into());
let arguments = arguments(
tail.strip_suffix(')').ok_or_else(invalid)?,
matches!(
name,
"abs" | "square" | "sqrt" | "real" | "sin" | "cos" | "tan"
),
)?;
if name == "rational" {
if arguments.len() != 2 {
return Err(invalid());
}
// Convert the complete exact ratio once. Its numerator or
// denominator may exceed binary64 while their quotient is finite.
use num_traits::{ToPrimitive, Zero};
let (n, d) = super::super::integer_queries::ratio_value(&format!(
"({}) / ({})",
arguments[0], arguments[1]
))?;
let nonzero = !n.is_zero();
let rational = num_rational::BigRational::new(n, d);
let base = rational
.to_f64()
.ok_or_else(|| Error("numeric_overflow".into()))?;
return Ok(Value {
base: super::checked_number(base, nonzero)?,
exact: (!self.standard)
.then(|| super::exact::bounded(rational, None))
.flatten(),
dimensions: Default::default(),
preferred: None,
affine_temperature: false,
});
}
let many = matches!(name, "min" | "max" | "mean" | "sum");
if arguments.is_empty()
|| (!many && arguments.len() != 1 && !(name == "round" && arguments.len() == 2))
{
return Err(invalid());
}
let mut values = arguments
.into_iter()
.map(|s| self.expression(s, depth + 1))
.collect::<Result<Vec<_>, _>>()?;
let mut value = values.remove(0);
if matches!(name, "sin" | "cos" | "tan") {
let angle = self.unit("rad").ok_or_else(invalid)?;
if value.affine_temperature
|| (!value.dimensions.is_empty() && value.dimensions != angle.dimensions)
{
return Err(Error("incompatible_units".into()));
}
// Typed angles are already in base radians; scalars retain the
// existing Arithmetic convention of scalar radian arguments.
let base = super::super::arithmetic::trig(name, value.base).ok_or_else(invalid)?;
return Ok(Value {
base: super::checked_number(base, false)?,
exact: None,
dimensions: Default::default(),
preferred: None,
affine_temperature: false,
});
}
let display = value.preferred.clone().or_else(|| {
self.seen
.iter()
.find(|u| u.dimensions == value.dimensions)
.cloned()
});
let precision =
name == "round" && values.first().is_some_and(|v| v.dimensions.is_empty());
if !precision && values.iter().any(|v| v.dimensions != value.dimensions) {
return Err(Error("incompatible_units".into()));
}
if (value.affine_temperature || values.iter().any(|v| v.affine_temperature))
&& !matches!(name, "min" | "max" | "mean" | "abs" | "round")
{
return Err(Error("affine_unit_in_rate".into()));
}
let exact_abs = (name == "abs" && display.as_ref().is_none_or(|u| u.offset == 0.0))
.then(|| value.exact.clone())
.flatten();
match name {
"real" => {
if !value.dimensions.is_empty() {
return Err(Error("incompatible_units".into()));
}
}
"min" => value.base = values.iter().fold(value.base, |a, b| a.min(b.base)),
"max" => value.base = values.iter().fold(value.base, |a, b| a.max(b.base)),
"mean" if !self.standard => {
let count = (values.len() + 1) as f64;
let bases = std::iter::once(value.base).chain(values.iter().map(|v| v.base));
// Use the same compensated accumulation as Probability's weighted
// mean. A finite total is divided last, preserving tiny equal inputs.
let total = compensated_sum(bases.clone());
value.base = if total.is_finite() {
super::checked_number(total / count, total != 0.0)?
} else {
// Dividing before adding bounds finite same-sign extremes.
// Aggregate tiny terms before dividing: their combined mean
// may be representable even when each divided term is zero.
let lost = compensated_sum(
bases
.clone()
.filter(|base| *base != 0.0 && *base / count == 0.0),
);
let residual = lost / count;
let mean = compensated_sum(bases.map(|base| base / count)) + residual;
super::checked_number(
mean,
mean != 0.0 || (lost != 0.0 && residual == 0.0),
)?
};
}
"mean" | "sum" => {
// Standard mode retains its operation order.
value.base += values.iter().map(|v| v.base).sum::<f64>();
if name == "mean" {
value.base = super::checked_number(
value.base / (values.len() + 1) as f64,
value.base != 0.0,
)?;
}
}
"abs" => {
let offset = display.as_ref().map_or(0.0, |u| u.offset);
value.base = (value.base - offset).abs() + offset;
}
"round" => {
let scale = display.as_ref().map_or(1.0, |u| u.scale);
let offset = if precision || values.is_empty() {
display.as_ref().map_or(0.0, |u| u.offset)
} else {
0.0
};
if !precision && values.iter().any(|v| v.affine_temperature) {
return Err(Error("affine_unit_in_rate".into()));
}
let increment = if precision {
let places = values[0].base;
if places.fract() != 0.0 || !(0.0..=15.0).contains(&places) {
return Err(Error("invalid_rounding_precision".into()));
}
scale * 10.0_f64.powi(-(places as i32))
} else {
values.first().map_or(scale, |v| v.base)
};
if increment <= 0.0 || !increment.is_finite() {
return Err(Error("invalid_rounding_increment".into()));
}
let ratio = (value.base - offset) / increment;
// Decimal unit scales can put an exact half one ulp below the tie.
let magnitude = ratio.abs();
let tolerance = 8.0 * f64::EPSILON * magnitude.clamp(1.0, 1e6);
let rounded = if (magnitude.fract() - 0.5).abs() <= tolerance {
(magnitude.floor() + 1.0).copysign(ratio)
} else {
ratio.round()
};
value.base = rounded * increment + offset;
}
"square" | "sqrt" => {
let square = name == "square";
if !square
&& (value.base < 0.0 || value.dimensions.values().any(|p| p % 2 != 0))
{
return Err(Error("incompatible_units".into()));
}
value.base = if square {
super::checked_number(value.base * value.base, value.base != 0.0)?
} else {
value.base.sqrt()
};
for exponent in value.dimensions.values_mut() {
*exponent = if square {
exponent.checked_mul(2).ok_or_else(invalid)?
} else {
*exponent / 2
};
}
value.preferred = display.as_ref().and_then(|unit| {
if square {
if unit.name.contains(['/', '·', '⋅', '*']) {
return None;
}
let name = self
.units
.unit(&format!("square {}", unit.name))
.filter(|u| super::physical(u) == value.dimensions)
.map_or_else(|| format!("({})^2", unit.name), |u| u.symbol);
Some(DisplayUnit {
name,
scale: unit.scale * unit.scale,
dimensions: value.dimensions.clone(),
currency: false,
offset: 0.0,
})
} else {
// Prefer the source unit's root; otherwise use the registry's base unit.
unit.name
.strip_suffix('²')
.and_then(|name| self.unit(name))
.or_else(|| {
unit.name
.strip_prefix('(')?
.strip_suffix(")^2")
.and_then(|name| self.unit(name))
})
.or_else(|| {
self.units
.units
.iter()
.find(|u| {
super::physical(u) == value.dimensions
&& u.scale == 1.0
&& u.offset == 0.0
})
.and_then(|u| self.unit(&u.symbol))
})
}
});
}
_ => unreachable!(),
}
value.exact = if name == "abs" {
exact_abs.and_then(|mut exact| {
exact.amount = exact.amount.abs();
super::exact::bounded(exact.amount, exact.currency)
})
} else {
None
};
if !matches!(name, "square" | "sqrt") {
value.preferred = display;
}
if !value.base.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(value)
})())
}
}
pub(in crate::plugins) fn arguments(input: &str, unary: bool) -> Result<Vec<&str>, Error> {
let mut values = vec![];
let (mut depth, mut start) = (0i32, 0);
for (index, ch) in input.char_indices() {
match ch {
'(' => depth += 1,
')' => depth -= 1,
',' if depth == 0 => {
// A compact three-digit group inside a numeric literal is a thousands separator.
let tail = &input[index + 1..];
let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
if digits == 3
&& input[..index]
.chars()
.next_back()
.is_some_and(|c| c.is_ascii_digit())
&& ((tail.len() == 3 && unary)
|| tail[3..]
.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || matches!(c, ',' | '.' | ' ')))
{
continue;
}
values.push(input[start..index].trim());
start = index + 1;
}
_ => {}
}
if depth < 0 {
return Err(Error("invalid_expression".into()));
}
}
values.push(input[start..].trim());
if depth != 0 || values.iter().any(|s| s.is_empty()) {
return Err(Error("invalid_expression".into()));
}
Ok(values)
}
/// Neumaier summation retains small contributions between cancelling finite terms.
fn compensated_sum(values: impl Iterator<Item = f64>) -> f64 {
let (mut sum, mut correction) = (0.0_f64, 0.0_f64);
for value in values {
let next = sum + value;
correction += if sum.abs() >= value.abs() {
(sum - next) + value
} else {
(value - next) + sum
};
sum = next;
}
sum + correction
}