interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / research / atemporal / at1 / evaluator / src / rat.rs

313 lines · 9883 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Exact rationals, Gaussian rationals, the contract's token grammars
17//! (rational, complex rational, scaled decimal, integer) and the exact value
18//! of a binary64 bit pattern.
19
20use crate::big::Int;
21use std::cmp::Ordering;
22
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct Q {
25 pub n: Int,
26 pub d: Int, // > 0, gcd(|n|, d) = 1
27}
28
29impl Q {
30 pub fn new(n: Int, d: Int) -> Q {
31 assert!(!d.is_zero(), "zero denominator");
32 let (n, d) = if d.is_neg() { (n.neg(), d.neg()) } else { (n, d) };
33 let g = Int::gcd(&n, &d);
34 if g.is_zero() || g == Int::from_u64(1) {
35 if n.is_zero() {
36 return Q { n, d: Int::from_u64(1) };
37 }
38 return Q { n, d };
39 }
40 Q { n: n.divrem(&g).0, d: d.divrem(&g).0 }
41 }
42 pub fn int(v: i64) -> Q {
43 Q { n: Int::from_i64(v), d: Int::from_u64(1) }
44 }
45 pub fn frac(n: i64, d: i64) -> Q {
46 Q::new(Int::from_i64(n), Int::from_i64(d))
47 }
48 pub fn zero() -> Q {
49 Q::int(0)
50 }
51 pub fn one() -> Q {
52 Q::int(1)
53 }
54 pub fn is_zero(&self) -> bool {
55 self.n.is_zero()
56 }
57 pub fn add(&self, o: &Q) -> Q {
58 if self.d == o.d {
59 return Q::new(self.n.add(&o.n), self.d.clone());
60 }
61 Q::new(self.n.mul(&o.d).add(&o.n.mul(&self.d)), self.d.mul(&o.d))
62 }
63 pub fn sub(&self, o: &Q) -> Q {
64 self.add(&o.neg())
65 }
66 pub fn mul(&self, o: &Q) -> Q {
67 Q::new(self.n.mul(&o.n), self.d.mul(&o.d))
68 }
69 pub fn div(&self, o: &Q) -> Q {
70 assert!(!o.is_zero(), "division by zero rational");
71 Q::new(self.n.mul(&o.d), self.d.mul(&o.n))
72 }
73 pub fn neg(&self) -> Q {
74 Q { n: self.n.neg(), d: self.d.clone() }
75 }
76 pub fn abs(&self) -> Q {
77 Q { n: self.n.abs(), d: self.d.clone() }
78 }
79 pub fn cmp(&self, o: &Q) -> Ordering {
80 self.n.mul(&o.d).cmp(&o.n.mul(&self.d))
81 }
82 pub fn signum(&self) -> i32 {
83 self.n.signum()
84 }
85 pub fn is_int(&self) -> bool {
86 self.d == Int::from_u64(1)
87 }
88 pub fn floor(&self) -> Int {
89 self.n.div_floor(&self.d).0
90 }
91 /// self - floor(self), in [0, 1).
92 pub fn mod1(&self) -> Q {
93 let (_, r) = self.n.div_floor(&self.d);
94 Q::new(r, self.d.clone())
95 }
96 /// Exact square root when self is the square of a rational.
97 pub fn sqrt_exact(&self) -> Option<Q> {
98 if self.n.is_neg() {
99 return None;
100 }
101 let a = self.n.isqrt();
102 let b = self.d.isqrt();
103 if a.mul(&a) == self.n && b.mul(&b) == self.d {
104 Some(Q { n: a, d: b })
105 } else {
106 None
107 }
108 }
109 /// Exact value of a finite binary64 bit pattern.
110 pub fn from_f64_bits(bits: u64) -> Q {
111 let neg = bits >> 63 == 1;
112 let e = ((bits >> 52) & 0x7ff) as i32;
113 let f = bits & ((1u64 << 52) - 1);
114 assert!(e != 0x7ff, "non-finite pattern");
115 let (m, exp) = if e == 0 { (f, -1074) } else { (f | (1u64 << 52), e - 1075) };
116 let mi = Int::from_u64(m);
117 let mi = if neg { mi.neg() } else { mi };
118 if exp >= 0 {
119 Q::new(mi.shl(exp as u32), Int::from_u64(1))
120 } else {
121 Q::new(mi, Int::pow2((-exp) as u32))
122 }
123 }
124 /// Scaled decimal N@k as an exact rational.
125 pub fn from_scaled(s: &Scaled) -> Q {
126 Q::new(s.n.clone(), Int::pow10(s.k))
127 }
128 /// Nearest-ish binary64 (for display and for seeding double-double only).
129 pub fn to_f64(&self) -> f64 {
130 let dd = crate::dd::Dd::from_q(self);
131 dd.hi
132 }
133 pub fn text(&self) -> String {
134 format!("{}/{}", self.n.to_dec(), self.d.to_dec())
135 }
136 /// Within the AT1_CASE_V1 section 2 token limits.
137 pub fn within_limits(&self) -> bool {
138 let lim = Int::from_u64(1_048_576);
139 self.n.abs().cmp(&lim) != Ordering::Greater && self.d.cmp(&lim) != Ordering::Greater
140 }
141}
142
143/// Gaussian rational.
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub struct Cq {
146 pub re: Q,
147 pub im: Q,
148}
149
150impl Cq {
151 pub fn new(re: Q, im: Q) -> Cq {
152 Cq { re, im }
153 }
154 pub fn zero() -> Cq {
155 Cq::new(Q::zero(), Q::zero())
156 }
157 pub fn real(q: Q) -> Cq {
158 Cq::new(q, Q::zero())
159 }
160 pub fn is_zero(&self) -> bool {
161 self.re.is_zero() && self.im.is_zero()
162 }
163 pub fn add(&self, o: &Cq) -> Cq {
164 Cq::new(self.re.add(&o.re), self.im.add(&o.im))
165 }
166 pub fn sub(&self, o: &Cq) -> Cq {
167 Cq::new(self.re.sub(&o.re), self.im.sub(&o.im))
168 }
169 pub fn mul(&self, o: &Cq) -> Cq {
170 Cq::new(
171 self.re.mul(&o.re).sub(&self.im.mul(&o.im)),
172 self.re.mul(&o.im).add(&self.im.mul(&o.re)),
173 )
174 }
175 pub fn conj(&self) -> Cq {
176 Cq::new(self.re.clone(), self.im.neg())
177 }
178 pub fn norm2(&self) -> Q {
179 self.re.mul(&self.re).add(&self.im.mul(&self.im))
180 }
181 pub fn scale(&self, q: &Q) -> Cq {
182 Cq::new(self.re.mul(q), self.im.mul(q))
183 }
184}
185
186/// Scaled decimal N@k.
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct Scaled {
189 pub n: Int,
190 pub k: u32,
191}
192
193/// Outcome of parsing a token against its grammar.
194#[derive(Clone, Copy, Debug, PartialEq, Eq)]
195pub enum Tok {
196 Ok,
197 /// parsed, but not the canonical spelling (CASE_NONCANONICAL after the shape pass)
198 NonCanonical,
199}
200
201/// Integer text: optional '-', digits. Returns the value and canonicality; None if not an integer at all.
202pub fn parse_int(s: &str) -> Option<(Int, Tok)> {
203 let (neg, digits) = match s.strip_prefix('-') {
204 Some(rest) => (true, rest),
205 None => (false, s),
206 };
207 let v = Int::from_dec_digits(digits)?;
208 let mut t = Tok::Ok;
209 if digits.len() > 1 && digits.starts_with('0') {
210 t = Tok::NonCanonical;
211 }
212 if neg && v.is_zero() {
213 t = Tok::NonCanonical;
214 }
215 Some((if neg { v.neg() } else { v }, t))
216}
217
218/// Rational n/d with d >= 1 (d < 1 is shape). Value is reduced; Tok says if the spelling was canonical.
219pub fn parse_rat(s: &str) -> Option<(Q, Tok)> {
220 let (a, b) = s.split_once('/')?;
221 let (n, t1) = parse_int(a)?;
222 if b.starts_with('-') {
223 return None;
224 }
225 let (d, t2) = parse_int(b)?;
226 if d.signum() < 1 {
227 return None;
228 }
229 let mut t = if t1 == Tok::Ok && t2 == Tok::Ok { Tok::Ok } else { Tok::NonCanonical };
230 let g = Int::gcd(&n, &d);
231 if n.is_zero() {
232 if d != Int::from_u64(1) {
233 t = Tok::NonCanonical;
234 }
235 } else if g != Int::from_u64(1) {
236 t = Tok::NonCanonical;
237 }
238 Some((Q::new(n, d), t))
239}
240
241/// Complex rational (re;im).
242pub fn parse_crat(s: &str) -> Option<(Cq, Tok)> {
243 let inner = s.strip_prefix('(')?.strip_suffix(')')?;
244 let (a, b) = inner.split_once(';')?;
245 let (re, t1) = parse_rat(a)?;
246 let (im, t2) = parse_rat(b)?;
247 let t = if t1 == Tok::Ok && t2 == Tok::Ok { Tok::Ok } else { Tok::NonCanonical };
248 Some((Cq::new(re, im), t))
249}
250
251/// Scaled decimal N@k, 0 <= k <= 40.
252pub fn parse_scaled(s: &str) -> Option<(Scaled, Tok)> {
253 let (a, b) = s.split_once('@')?;
254 let n = Int::from_dec_digits(a)?;
255 let kv = Int::from_dec_digits(b)?;
256 if b.len() > 2 {
257 return None;
258 }
259 let k = kv.low_u64() as u32;
260 if k > 40 {
261 return None;
262 }
263 let mut t = Tok::Ok;
264 if a.len() > 1 && a.starts_with('0') {
265 t = Tok::NonCanonical;
266 }
267 if b.len() > 1 && b.starts_with('0') {
268 t = Tok::NonCanonical;
269 }
270 if n.is_zero() && k != 0 {
271 t = Tok::NonCanonical;
272 }
273 if !n.is_zero() && k != 0 && n.divrem(&Int::from_u64(10)).1.is_zero() {
274 t = Tok::NonCanonical;
275 }
276 Some((Scaled { n, k }, t))
277}
278
279pub fn scaled_text(s: &Scaled) -> String {
280 format!("{}@{}", s.n.to_dec(), s.k)
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286 #[test]
287 fn grammars() {
288 assert_eq!(parse_rat("2/4").unwrap().1, Tok::NonCanonical);
289 assert_eq!(parse_rat("-0/1").unwrap().1, Tok::NonCanonical);
290 assert_eq!(parse_rat("0/2").unwrap().1, Tok::NonCanonical);
291 assert_eq!(parse_rat("3/10").unwrap(), (Q::frac(3, 10), Tok::Ok));
292 assert!(parse_rat("1/0").is_none());
293 assert!(parse_rat("1/-2").is_none());
294 assert!(parse_rat("0.25").is_none());
295 assert!(parse_rat("+1/2").is_none());
296 assert_eq!(parse_int("04").unwrap().1, Tok::NonCanonical);
297 assert_eq!(parse_scaled("10@1").unwrap().1, Tok::NonCanonical);
298 assert_eq!(parse_scaled("0@3").unwrap().1, Tok::NonCanonical);
299 assert_eq!(parse_scaled("1@12").unwrap().1, Tok::Ok);
300 assert!(parse_scaled("1@41").is_none());
301 assert_eq!(parse_crat("(1/1;0/1)").unwrap().1, Tok::Ok);
302 assert!(parse_crat("(1/1,0/1)").is_none());
303 }
304 #[test]
305 fn f64_exact() {
306 assert_eq!(Q::from_f64_bits(0.25f64.to_bits()), Q::frac(1, 4));
307 assert_eq!(Q::from_f64_bits((-3.0f64).to_bits()), Q::int(-3));
308 assert_eq!(Q::from_f64_bits(1), Q::new(Int::from_u64(1), Int::pow2(1074)));
309 assert_eq!(Q::frac(41, 100).sqrt_exact(), None);
310 assert_eq!(Q::frac(1, 4).sqrt_exact(), Some(Q::frac(1, 2)));
311 assert_eq!(Q::frac(-7, 4).mod1(), Q::frac(1, 4));
312 }
313}