1use std::cmp::Ordering;
2use std::fmt;
3use std::ops::{Add, Div, Mul, Neg, Sub};
4
5use anyhow::{anyhow, ensure, Result};
6use num_complex::{Complex32, Complex64};
7use num_traits::{One, Zero};
8use tenferro::{DType, Tensor as NativeTensor, TensorScalar};
9
10use crate::storage::{Storage, SumFromStorage};
11use crate::tensor_element::TensorElement;
12
13#[derive(Clone, Copy, Debug, PartialEq)]
29pub enum ScalarValue {
30 F32(f32),
32 F64(f64),
34 I32(i32),
36 I64(i64),
38 Bool(bool),
40 C32(Complex32),
42 C64(Complex64),
44}
45
46impl From<f64> for ScalarValue {
47 fn from(value: f64) -> Self {
48 Self::F64(value)
49 }
50}
51
52impl From<f32> for ScalarValue {
53 fn from(value: f32) -> Self {
54 Self::F32(value)
55 }
56}
57
58impl From<Complex64> for ScalarValue {
59 fn from(value: Complex64) -> Self {
60 Self::C64(value)
61 }
62}
63
64impl From<Complex32> for ScalarValue {
65 fn from(value: Complex32) -> Self {
66 Self::C32(value)
67 }
68}
69
70impl ScalarValue {
71 pub fn real(self) -> f64 {
73 match self {
74 Self::F32(value) => value as f64,
75 Self::F64(value) => value,
76 Self::I32(value) => value as f64,
77 Self::I64(value) => value as f64,
78 Self::Bool(value) => {
79 if value {
80 1.0
81 } else {
82 0.0
83 }
84 }
85 Self::C32(value) => value.re as f64,
86 Self::C64(value) => value.re,
87 }
88 }
89
90 pub fn imag(self) -> f64 {
92 match self {
93 Self::F32(_) | Self::F64(_) | Self::I32(_) | Self::I64(_) | Self::Bool(_) => 0.0,
94 Self::C32(value) => value.im as f64,
95 Self::C64(value) => value.im,
96 }
97 }
98
99 pub fn abs(self) -> f64 {
108 match self {
109 Self::F32(value) => value.abs() as f64,
110 Self::F64(value) => value.abs(),
111 Self::I32(value) => f64::from(value).abs(),
112 Self::I64(value) => (value as f64).abs(),
113 Self::Bool(value) => {
114 if value {
115 1.0
116 } else {
117 0.0
118 }
119 }
120 Self::C32(value) => {
123 if value.re.is_nan() || value.im.is_nan() {
124 f64::NAN
125 } else {
126 f64::from(value.re).hypot(f64::from(value.im))
127 }
128 }
129 Self::C64(value) => {
130 if value.re.is_nan() || value.im.is_nan() {
131 f64::NAN
132 } else {
133 value.re.hypot(value.im)
134 }
135 }
136 }
137 }
138
139 pub fn is_complex(self) -> bool {
141 matches!(self, Self::C32(_) | Self::C64(_))
142 }
143
144 pub fn is_zero(self) -> bool {
146 match self {
147 Self::F32(value) => value == 0.0,
148 Self::F64(value) => value == 0.0,
149 Self::I32(value) => value == 0,
150 Self::I64(value) => value == 0,
151 Self::Bool(value) => !value,
152 Self::C32(value) => value == Complex32::new(0.0, 0.0),
153 Self::C64(value) => value == Complex64::new(0.0, 0.0),
154 }
155 }
156
157 pub fn into_complex(self) -> Complex64 {
159 match self {
160 Self::F32(value) => Complex64::new(value as f64, 0.0),
161 Self::F64(value) => Complex64::new(value, 0.0),
162 Self::I32(value) => Complex64::new(value as f64, 0.0),
163 Self::I64(value) => Complex64::new(value as f64, 0.0),
164 Self::Bool(value) => Complex64::new(if value { 1.0 } else { 0.0 }, 0.0),
165 Self::C32(value) => Complex64::new(value.re as f64, value.im as f64),
166 Self::C64(value) => value,
167 }
168 }
169}
170
171fn scalar_value_from_storage(storage: &Storage) -> ScalarValue {
177 match storage.dtype() {
178 DType::F32 => ScalarValue::F32(f32::sum_from_storage(storage)),
179 DType::F64 => ScalarValue::F64(f64::sum_from_storage(storage)),
180 DType::C32 => ScalarValue::C32(Complex32::sum_from_storage(storage)),
181 DType::C64 => ScalarValue::C64(Complex64::sum_from_storage(storage)),
182 other => crate::invariant_violated(
184 "compact storage reduction",
185 format!("compact storage carries no {other:?} payload"),
186 ),
187 }
188}
189
190fn scalar_value_from_native(native: &NativeTensor) -> Result<ScalarValue> {
191 ensure!(
192 native.shape().is_empty(),
193 "expected rank-0 scalar tensor, got shape {:?}",
194 native.shape()
195 );
196
197 match native.dtype() {
198 DType::F32 => native
199 .as_slice::<f32>()
200 .map_err(anyhow::Error::new)?
201 .first()
202 .copied()
203 .map(ScalarValue::F32)
204 .ok_or_else(|| anyhow!("failed to read f32 scalar tensor value")),
205 DType::F64 => native
206 .as_slice::<f64>()
207 .map_err(anyhow::Error::new)?
208 .first()
209 .copied()
210 .map(ScalarValue::F64)
211 .ok_or_else(|| anyhow!("failed to read f64 scalar tensor value")),
212 DType::I32 => native
213 .as_slice::<i32>()
214 .map_err(anyhow::Error::new)?
215 .first()
216 .copied()
217 .map(ScalarValue::I32)
218 .ok_or_else(|| anyhow!("failed to read i32 scalar tensor value")),
219 DType::I64 => native
220 .as_slice::<i64>()
221 .map_err(anyhow::Error::new)?
222 .first()
223 .copied()
224 .map(ScalarValue::I64)
225 .ok_or_else(|| anyhow!("failed to read i64 scalar tensor value")),
226 DType::Bool => native
227 .as_slice::<bool>()
228 .map_err(anyhow::Error::new)?
229 .first()
230 .copied()
231 .map(ScalarValue::Bool)
232 .ok_or_else(|| anyhow!("failed to read bool scalar tensor value")),
233 DType::C32 => native
234 .as_slice::<Complex32>()
235 .map_err(anyhow::Error::new)?
236 .first()
237 .copied()
238 .map(ScalarValue::C32)
239 .ok_or_else(|| anyhow!("failed to read c32 scalar tensor value")),
240 DType::External(_) => Err(anyhow::Error::new(tenferro_tensor::Error::unsupported(
243 "scalar snapshot",
244 format!(
245 "external scalar kind {:?} is not a supported scalar tensor",
246 native.dtype()
247 ),
248 ))),
249 DType::C64 => native
250 .as_slice::<Complex64>()
251 .map_err(anyhow::Error::new)?
252 .first()
253 .copied()
254 .map(ScalarValue::C64)
255 .ok_or_else(|| anyhow!("failed to read c64 scalar tensor value")),
256 }
257}
258
259pub trait ScalarTensorElement: TensorElement {
278 fn scalar_value(value: Self) -> ScalarValue;
280}
281
282fn scalar_native<T: TensorScalar>(value: T) -> NativeTensor {
283 NativeTensor::from_vec_col_major(vec![], vec![value]).unwrap_or_else(|error| {
284 crate::invariant_violated("rank-0 scalar construction failed", error)
285 })
286}
287
288impl ScalarTensorElement for f32 {
289 fn scalar_value(value: Self) -> ScalarValue {
290 ScalarValue::F32(value)
291 }
292}
293
294impl ScalarTensorElement for f64 {
295 fn scalar_value(value: Self) -> ScalarValue {
296 ScalarValue::F64(value)
297 }
298}
299
300impl ScalarTensorElement for Complex32 {
301 fn scalar_value(value: Self) -> ScalarValue {
302 ScalarValue::C32(value)
303 }
304}
305
306impl ScalarTensorElement for Complex64 {
307 fn scalar_value(value: Self) -> ScalarValue {
308 ScalarValue::C64(value)
309 }
310}
311
312pub(crate) fn promote_scalar_native(native: &NativeTensor, target: DType) -> Result<NativeTensor> {
313 let promoted = match (scalar_value_from_native(native)?, target) {
314 (ScalarValue::F32(value), DType::F32) => BackendScalar::from_value(value),
315 (ScalarValue::F32(value), DType::F64) => BackendScalar::from_value(value as f64),
316 (ScalarValue::F32(value), DType::C32) => {
317 BackendScalar::from_value(Complex32::new(value, 0.0))
318 }
319 (ScalarValue::F32(value), DType::C64) => {
320 BackendScalar::from_value(Complex64::new(value as f64, 0.0))
321 }
322 (ScalarValue::F32(_), DType::I64) => {
323 return Err(anyhow!(
324 "cannot promote f32 scalar to i64 without truncation"
325 ));
326 }
327 (ScalarValue::F32(_), DType::I32 | DType::Bool) => {
328 return Err(anyhow!(
329 "cannot promote f32 scalar to integer/bool without truncation"
330 ));
331 }
332 (ScalarValue::F64(value), DType::F32) => BackendScalar::from_value(value as f32),
333 (ScalarValue::F64(value), DType::F64) => BackendScalar::from_value(value),
334 (ScalarValue::F64(_), DType::I64) => {
335 return Err(anyhow!(
336 "cannot promote f64 scalar to i64 without truncation"
337 ));
338 }
339 (ScalarValue::F64(_), DType::I32 | DType::Bool) => {
340 return Err(anyhow!(
341 "cannot promote f64 scalar to integer/bool without truncation"
342 ));
343 }
344 (ScalarValue::F64(value), DType::C32) => {
345 BackendScalar::from_value(Complex32::new(value as f32, 0.0))
346 }
347 (ScalarValue::F64(value), DType::C64) => {
348 BackendScalar::from_value(Complex64::new(value, 0.0))
349 }
350 (ScalarValue::I32(value), DType::F32) => BackendScalar::from_value(value as f32),
351 (ScalarValue::I32(value), DType::F64) => BackendScalar::from_value(value as f64),
352 (ScalarValue::I32(value), DType::I32) => return Ok(scalar_native(value)),
353 (ScalarValue::I32(value), DType::I64) => BackendScalar::from_i64(value as i64),
354 (ScalarValue::I32(value), DType::C32) => {
355 BackendScalar::from_value(Complex32::new(value as f32, 0.0))
356 }
357 (ScalarValue::I32(value), DType::C64) => {
358 BackendScalar::from_value(Complex64::new(value as f64, 0.0))
359 }
360 (ScalarValue::I32(_), DType::Bool) => {
361 return Err(anyhow!("cannot promote i32 scalar to bool"));
362 }
363 (ScalarValue::I64(value), DType::F32) => BackendScalar::from_value(value as f32),
364 (ScalarValue::I64(value), DType::F64) => BackendScalar::from_value(value as f64),
365 (ScalarValue::I64(_), DType::I32 | DType::Bool) => {
366 return Err(anyhow!("cannot promote i64 scalar to i32/bool"));
367 }
368 (ScalarValue::I64(value), DType::I64) => BackendScalar::from_i64(value),
369 (ScalarValue::I64(value), DType::C32) => {
370 BackendScalar::from_value(Complex32::new(value as f32, 0.0))
371 }
372 (ScalarValue::I64(value), DType::C64) => {
373 BackendScalar::from_value(Complex64::new(value as f64, 0.0))
374 }
375 (ScalarValue::Bool(value), DType::F32) => {
376 BackendScalar::from_value(if value { 1.0_f32 } else { 0.0_f32 })
377 }
378 (ScalarValue::Bool(value), DType::F64) => {
379 BackendScalar::from_value(if value { 1.0 } else { 0.0 })
380 }
381 (ScalarValue::Bool(value), DType::I32) => {
382 return Ok(scalar_native(if value { 1 } else { 0 }));
383 }
384 (ScalarValue::Bool(value), DType::I64) => {
385 BackendScalar::from_i64(if value { 1 } else { 0 })
386 }
387 (ScalarValue::Bool(value), DType::Bool) => return Ok(scalar_native(value)),
388 (ScalarValue::Bool(value), DType::C32) => {
389 BackendScalar::from_value(Complex32::new(if value { 1.0 } else { 0.0 }, 0.0))
390 }
391 (ScalarValue::Bool(value), DType::C64) => {
392 BackendScalar::from_value(Complex64::new(if value { 1.0 } else { 0.0 }, 0.0))
393 }
394 (ScalarValue::C32(value), DType::F32) => BackendScalar::from_value(value.re),
395 (ScalarValue::C32(value), DType::F64) => BackendScalar::from_value(value.re as f64),
396 (ScalarValue::C32(_), DType::I32 | DType::I64 | DType::Bool) => {
397 return Err(anyhow!("cannot promote c32 scalar to integer/bool"));
398 }
399 (ScalarValue::C32(value), DType::C32) => BackendScalar::from_value(value),
400 (ScalarValue::C32(value), DType::C64) => {
401 BackendScalar::from_value(Complex64::new(value.re as f64, value.im as f64))
402 }
403 (ScalarValue::C64(value), DType::F32) => BackendScalar::from_value(value.re as f32),
404 (ScalarValue::C64(value), DType::F64) => BackendScalar::from_value(value.re),
405 (ScalarValue::C64(_), DType::I32 | DType::I64 | DType::Bool) => {
406 return Err(anyhow!("cannot promote c64 scalar to integer/bool"));
407 }
408 (ScalarValue::C64(value), DType::C32) => {
409 BackendScalar::from_value(Complex32::new(value.re as f32, value.im as f32))
410 }
411 (ScalarValue::C64(value), DType::C64) => BackendScalar::from_value(value),
412
413 (_, DType::External(_)) => {
414 return Err(anyhow::Error::new(tenferro_tensor::Error::unsupported(
415 "promotion",
416 "external scalar kinds are not promotable dtypes",
417 )));
418 }
419 };
420 Ok(promoted.native)
421}
422
423pub struct BackendScalar {
451 native: NativeTensor,
452 value: ScalarValue,
453}
454
455impl BackendScalar {
456 fn wrap_native(native: NativeTensor) -> Result<Self> {
457 if native.shape().is_empty() {
458 let value = scalar_value_from_native(&native)?;
459 Ok(Self { native, value })
460 } else {
461 Err(anyhow!(
462 "BackendScalar requires a rank-0 tensor, got shape {:?}",
463 native.shape()
464 ))
465 }
466 }
467
468 fn value(&self) -> ScalarValue {
469 self.value
470 }
471
472 fn from_i64(value: i64) -> Self {
473 Self {
474 native: scalar_native(value),
475 value: ScalarValue::I64(value),
476 }
477 }
478
479 fn from_i32(value: i32) -> Self {
480 Self {
481 native: scalar_native(value),
482 value: ScalarValue::I32(value),
483 }
484 }
485
486 fn from_bool(value: bool) -> Self {
487 Self {
488 native: scalar_native(value),
489 value: ScalarValue::Bool(value),
490 }
491 }
492
493 pub(crate) fn from_native(value: NativeTensor) -> Result<Self> {
494 Self::wrap_native(value)
495 }
496
497 pub(crate) fn as_native(&self) -> &NativeTensor {
498 &self.native
499 }
500
501 pub fn from_value<T: ScalarTensorElement>(value: T) -> Self {
518 Self {
519 native: scalar_native(value),
520 value: T::scalar_value(value),
521 }
522 }
523
524 pub fn from_real(x: f64) -> Self {
536 Self::from_value(x)
537 }
538
539 pub fn from_complex(re: f64, im: f64) -> Self {
552 Self::from_value(Complex64::new(re, im))
553 }
554
555 pub fn new_real(x: f64) -> Self {
566 Self::from_real(x)
567 }
568
569 pub fn new_complex(re: f64, im: f64) -> Self {
580 Self::from_complex(re, im)
581 }
582
583 pub fn primal(&self) -> Self {
595 self.clone()
596 }
597
598 pub fn real(&self) -> f64 {
609 self.value().real()
610 }
611
612 pub fn imag(&self) -> f64 {
628 self.value().imag()
629 }
630
631 pub fn abs(&self) -> f64 {
647 self.value().abs()
648 }
649
650 pub fn is_complex(&self) -> bool {
661 self.value().is_complex()
662 }
663
664 pub fn is_real(&self) -> bool {
675 !self.is_complex()
676 }
677
678 pub fn is_zero(&self) -> bool {
689 self.value().is_zero()
690 }
691
692 pub fn as_f64(&self) -> Option<f64> {
708 match self.value() {
709 ScalarValue::F32(value) => Some(value as f64),
710 ScalarValue::F64(value) => Some(value),
711 ScalarValue::I32(value) => Some(value as f64),
712 ScalarValue::I64(value) => Some(value as f64),
713 ScalarValue::Bool(value) => Some(if value { 1.0 } else { 0.0 }),
714 ScalarValue::C32(_) | ScalarValue::C64(_) => None,
715 }
716 }
717
718 pub fn as_c64(&self) -> Option<Complex64> {
735 match self.value() {
736 ScalarValue::F32(_)
737 | ScalarValue::F64(_)
738 | ScalarValue::I32(_)
739 | ScalarValue::I64(_)
740 | ScalarValue::Bool(_) => None,
741 ScalarValue::C32(value) => Some(Complex64::new(value.re as f64, value.im as f64)),
742 ScalarValue::C64(value) => Some(value),
743 }
744 }
745
746 pub fn conj(&self) -> Self {
764 match self.value() {
765 ScalarValue::F32(value) => Self::from_value(value),
766 ScalarValue::F64(value) => Self::from_value(value),
767 ScalarValue::I32(value) => Self::from_i32(value),
768 ScalarValue::I64(value) => Self::from_i64(value),
769 ScalarValue::Bool(value) => Self::from_bool(value),
770 ScalarValue::C32(value) => Self::from_value(value.conj()),
771 ScalarValue::C64(value) => Self::from_value(value.conj()),
772 }
773 }
774
775 pub fn real_part(&self) -> Self {
790 Self::from_real(self.real())
791 }
792
793 pub fn imag_part(&self) -> Self {
809 Self::from_real(self.imag())
810 }
811
812 pub fn compose_complex(real: Self, imag: Self) -> Result<Self> {
832 if !real.is_real() || !imag.is_real() {
833 return Err(anyhow!(
834 "compose_complex requires real-valued inputs, got real={:?}, imag={:?}",
835 real.native.dtype(),
836 imag.native.dtype()
837 ));
838 }
839 Ok(Self::from_complex(real.real(), imag.real()))
840 }
841
842 pub fn sqrt(&self) -> Self {
855 if self.is_complex() || self.real() < 0.0 {
856 let value = self.value().into_complex().sqrt();
857 if value.im == 0.0 {
858 Self::from_real(value.re)
859 } else {
860 Self::from_value(value)
861 }
862 } else {
863 Self::from_real(self.real().sqrt())
864 }
865 }
866
867 pub fn powf(&self, exponent: f64) -> Self {
881 let needs_complex_promotion =
882 self.is_complex() || (self.real() < 0.0 && exponent.fract() != 0.0);
883 if needs_complex_promotion {
884 let value = self.value().into_complex().powf(exponent);
885 if value.im == 0.0 {
886 Self::from_real(value.re)
887 } else {
888 Self::from_value(value)
889 }
890 } else {
891 Self::from_real(self.real().powf(exponent))
892 }
893 }
894
895 pub fn powi(&self, exponent: i32) -> Self {
906 self.powf(exponent as f64)
907 }
908}
909
910impl SumFromStorage for BackendScalar {
911 fn sum_from_storage(storage: &Storage) -> Self {
912 Self::from(scalar_value_from_storage(storage))
913 }
914}
915
916impl From<ScalarValue> for BackendScalar {
917 fn from(value: ScalarValue) -> Self {
918 match value {
919 ScalarValue::F32(value) => Self::from_value(value),
920 ScalarValue::F64(value) => Self::from_value(value),
921 ScalarValue::I32(value) => Self::from_i32(value),
922 ScalarValue::I64(value) => Self::from_i64(value),
923 ScalarValue::Bool(value) => Self::from_bool(value),
924 ScalarValue::C32(value) => Self::from_value(value),
925 ScalarValue::C64(value) => Self::from_value(value),
926 }
927 }
928}
929
930impl From<f32> for BackendScalar {
931 fn from(value: f32) -> Self {
932 Self::from_value(value)
933 }
934}
935
936impl From<f64> for BackendScalar {
937 fn from(value: f64) -> Self {
938 Self::from_value(value)
939 }
940}
941
942impl From<Complex32> for BackendScalar {
943 fn from(value: Complex32) -> Self {
944 Self::from_value(value)
945 }
946}
947
948impl From<Complex64> for BackendScalar {
949 fn from(value: Complex64) -> Self {
950 Self::from_value(value)
951 }
952}
953
954impl TryFrom<BackendScalar> for f64 {
955 type Error = &'static str;
956
957 fn try_from(value: BackendScalar) -> std::result::Result<Self, Self::Error> {
958 match value.value() {
959 ScalarValue::F32(real) => Ok(real as f64),
960 ScalarValue::F64(real) => Ok(real),
961 ScalarValue::I32(real) => Ok(real as f64),
962 ScalarValue::I64(real) => Ok(real as f64),
963 ScalarValue::Bool(real) => Ok(if real { 1.0 } else { 0.0 }),
964 ScalarValue::C32(_) | ScalarValue::C64(_) => {
965 Err("cannot convert complex scalar to f64")
966 }
967 }
968 }
969}
970
971impl From<BackendScalar> for Complex64 {
972 fn from(value: BackendScalar) -> Self {
973 value.value().into_complex()
974 }
975}
976
977impl Add for BackendScalar {
978 type Output = Self;
979
980 fn add(self, rhs: Self) -> Self::Output {
981 match (self.value(), rhs.value()) {
982 (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => Self::from_value(lhs + rhs),
983 (lhs, rhs) if lhs.is_complex() || rhs.is_complex() => {
984 Self::from_value(lhs.into_complex() + rhs.into_complex())
985 }
986 (lhs, rhs) => Self::from_real(lhs.real() + rhs.real()),
987 }
988 }
989}
990
991impl Sub for BackendScalar {
992 type Output = Self;
993
994 fn sub(self, rhs: Self) -> Self::Output {
995 self + (-rhs)
996 }
997}
998
999impl Mul for BackendScalar {
1000 type Output = Self;
1001
1002 fn mul(self, rhs: Self) -> Self::Output {
1003 match (self.value(), rhs.value()) {
1004 (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => Self::from_value(lhs * rhs),
1005 (lhs, rhs) if lhs.is_complex() || rhs.is_complex() => {
1006 Self::from_value(lhs.into_complex() * rhs.into_complex())
1007 }
1008 (lhs, rhs) => Self::from_real(lhs.real() * rhs.real()),
1009 }
1010 }
1011}
1012
1013impl Div for BackendScalar {
1014 type Output = Self;
1015
1016 fn div(self, rhs: Self) -> Self::Output {
1017 match (self.value(), rhs.value()) {
1018 (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => Self::from_value(lhs / rhs),
1019 (lhs, rhs) if lhs.is_complex() || rhs.is_complex() => {
1020 Self::from_value(divide_complex(lhs.into_complex(), rhs.into_complex()))
1021 }
1022 (lhs, rhs) => Self::from_real(lhs.real() / rhs.real()),
1023 }
1024 }
1025}
1026
1027fn divide_complex(lhs: Complex64, rhs: Complex64) -> Complex64 {
1028 if ![lhs.re, lhs.im, rhs.re, rhs.im]
1029 .iter()
1030 .all(|x| x.is_finite())
1031 || (rhs.re == 0.0 && rhs.im == 0.0)
1032 {
1033 return lhs / rhs;
1034 }
1035 if rhs.im == 0.0 {
1036 return Complex64::new(lhs.re / rhs.re, lhs.im / rhs.re);
1037 }
1038 if rhs.re == 0.0 {
1039 return Complex64::new(lhs.im / rhs.im, -lhs.re / rhs.im);
1040 }
1041 if [lhs.re, lhs.im, rhs.re, rhs.im]
1042 .iter()
1043 .all(|&x| has_plain_division_exponent(x))
1044 {
1045 return lhs / rhs;
1046 }
1047 let (a, ae) = split_binary(lhs.re);
1050 let (b, be) = split_binary(lhs.im);
1051 let (c, ce) = split_binary(rhs.re);
1052 let (d, de) = split_binary(rhs.im);
1053 let (denominator, exponent) = add_scaled((c * c, 2 * ce), (d * d, 2 * de));
1054 let (real, re) = add_scaled((a * c, ae + ce), (b * d, be + de));
1055 let (imag, im) = add_scaled((b * c, be + ce), (-a * d, ae + de));
1056 Complex64::new(
1057 scale_binary(real / denominator, re - exponent),
1058 scale_binary(imag / denominator, im - exponent),
1059 )
1060}
1061
1062fn has_plain_division_exponent(value: f64) -> bool {
1069 const BIAS: u64 = 1023;
1070 let biased = (value.to_bits() >> 52) & 0x7ff;
1071 value == 0.0 || (BIAS - 500..=BIAS + 500).contains(&biased)
1072}
1073
1074fn split_binary(value: f64) -> (f64, i32) {
1075 if value == 0.0 {
1076 return (value, 0);
1077 }
1078 let exponent = value.abs().log2().floor() as i32;
1081 (scale_binary(value, -exponent), exponent)
1082}
1083
1084fn add_scaled((x, xe): (f64, i32), (y, ye): (f64, i32)) -> (f64, i32) {
1085 let exponent = if x == 0.0 {
1086 ye
1087 } else if y == 0.0 {
1088 xe
1089 } else {
1090 xe.max(ye)
1091 };
1092 (
1093 scale_binary(x, xe - exponent) + scale_binary(y, ye - exponent),
1094 exponent,
1095 )
1096}
1097
1098fn scale_binary(mut value: f64, mut exponent: i32) -> f64 {
1099 while exponent != 0 {
1100 let chunk = exponent.clamp(-512, 512);
1101 value *= 2.0_f64.powi(chunk);
1102 exponent -= chunk;
1103 }
1104 value
1105}
1106
1107impl Neg for BackendScalar {
1108 type Output = Self;
1109
1110 fn neg(self) -> Self::Output {
1111 match self.value() {
1112 ScalarValue::F32(value) => Self::from_value(-value),
1113 ScalarValue::F64(value) => Self::from_value(-value),
1114 ScalarValue::I32(value) => Self::from_i32(-value),
1115 ScalarValue::I64(value) => Self::from_i64(-value),
1116 ScalarValue::Bool(value) => Self::from_real(if value { -1.0 } else { 0.0 }),
1117 ScalarValue::C32(value) => Self::from_value(-value),
1118 ScalarValue::C64(value) => Self::from_value(-value),
1119 }
1120 }
1121}
1122
1123impl Mul<BackendScalar> for f64 {
1124 type Output = BackendScalar;
1125
1126 fn mul(self, rhs: BackendScalar) -> Self::Output {
1127 BackendScalar::from_real(self) * rhs
1128 }
1129}
1130
1131impl Mul<BackendScalar> for Complex64 {
1132 type Output = BackendScalar;
1133
1134 fn mul(self, rhs: BackendScalar) -> Self::Output {
1135 BackendScalar::from(self) * rhs
1136 }
1137}
1138
1139impl Div<BackendScalar> for Complex64 {
1140 type Output = BackendScalar;
1141
1142 fn div(self, rhs: BackendScalar) -> Self::Output {
1143 BackendScalar::from(self) / rhs
1144 }
1145}
1146
1147impl Default for BackendScalar {
1148 fn default() -> Self {
1149 Self::zero()
1150 }
1151}
1152
1153impl Zero for BackendScalar {
1154 fn zero() -> Self {
1155 Self::from_real(0.0)
1156 }
1157
1158 fn is_zero(&self) -> bool {
1159 BackendScalar::is_zero(self)
1160 }
1161}
1162
1163impl One for BackendScalar {
1164 fn one() -> Self {
1165 Self::from_real(1.0)
1166 }
1167}
1168
1169impl PartialEq for BackendScalar {
1170 fn eq(&self, other: &Self) -> bool {
1171 self.native.dtype() == other.native.dtype() && self.value() == other.value()
1172 }
1173}
1174
1175impl PartialOrd for BackendScalar {
1176 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1177 match (self.value(), other.value()) {
1178 (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => lhs.partial_cmp(&rhs),
1179 (ScalarValue::F32(lhs), ScalarValue::F64(rhs)) => (lhs as f64).partial_cmp(&rhs),
1180 (ScalarValue::F32(lhs), ScalarValue::I32(rhs)) => {
1181 (lhs as f64).partial_cmp(&(rhs as f64))
1182 }
1183 (ScalarValue::F32(lhs), ScalarValue::I64(rhs)) => {
1184 (lhs as f64).partial_cmp(&(rhs as f64))
1185 }
1186 (ScalarValue::F32(lhs), ScalarValue::Bool(rhs)) => {
1187 (lhs as f64).partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1188 }
1189 (ScalarValue::F64(lhs), ScalarValue::F32(rhs)) => lhs.partial_cmp(&(rhs as f64)),
1190 (ScalarValue::F64(lhs), ScalarValue::F64(rhs)) => lhs.partial_cmp(&rhs),
1191 (ScalarValue::F64(lhs), ScalarValue::I32(rhs)) => lhs.partial_cmp(&(rhs as f64)),
1192 (ScalarValue::F64(lhs), ScalarValue::I64(rhs)) => lhs.partial_cmp(&(rhs as f64)),
1193 (ScalarValue::F64(lhs), ScalarValue::Bool(rhs)) => {
1194 lhs.partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1195 }
1196 (ScalarValue::I32(lhs), ScalarValue::F32(rhs)) => {
1197 (lhs as f64).partial_cmp(&(rhs as f64))
1198 }
1199 (ScalarValue::I32(lhs), ScalarValue::F64(rhs)) => (lhs as f64).partial_cmp(&rhs),
1200 (ScalarValue::I32(lhs), ScalarValue::I32(rhs)) => lhs.partial_cmp(&rhs),
1201 (ScalarValue::I32(lhs), ScalarValue::I64(rhs)) => {
1202 (lhs as f64).partial_cmp(&(rhs as f64))
1203 }
1204 (ScalarValue::I32(lhs), ScalarValue::Bool(rhs)) => {
1205 (lhs as f64).partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1206 }
1207 (ScalarValue::I64(lhs), ScalarValue::F32(rhs)) => {
1208 (lhs as f64).partial_cmp(&(rhs as f64))
1209 }
1210 (ScalarValue::I64(lhs), ScalarValue::F64(rhs)) => (lhs as f64).partial_cmp(&rhs),
1211 (ScalarValue::I64(lhs), ScalarValue::I32(rhs)) => {
1212 (lhs as f64).partial_cmp(&(rhs as f64))
1213 }
1214 (ScalarValue::I64(lhs), ScalarValue::I64(rhs)) => lhs.partial_cmp(&rhs),
1215 (ScalarValue::I64(lhs), ScalarValue::Bool(rhs)) => {
1216 (lhs as f64).partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1217 }
1218 (ScalarValue::Bool(lhs), ScalarValue::F32(rhs)) => {
1219 (if lhs { 1.0 } else { 0.0 }).partial_cmp(&(rhs as f64))
1220 }
1221 (ScalarValue::Bool(lhs), ScalarValue::F64(rhs)) => {
1222 (if lhs { 1.0 } else { 0.0 }).partial_cmp(&rhs)
1223 }
1224 (ScalarValue::Bool(lhs), ScalarValue::I32(rhs)) => {
1225 (if lhs { 1.0 } else { 0.0 }).partial_cmp(&(rhs as f64))
1226 }
1227 (ScalarValue::Bool(lhs), ScalarValue::I64(rhs)) => {
1228 (if lhs { 1.0 } else { 0.0 }).partial_cmp(&(rhs as f64))
1229 }
1230 (ScalarValue::Bool(lhs), ScalarValue::Bool(rhs)) => lhs.partial_cmp(&rhs),
1231 _ => None,
1232 }
1233 }
1234}
1235
1236impl fmt::Display for BackendScalar {
1237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1238 match self.value() {
1239 ScalarValue::F32(value) => value.fmt(f),
1240 ScalarValue::F64(value) => value.fmt(f),
1241 ScalarValue::I32(value) => value.fmt(f),
1242 ScalarValue::I64(value) => value.fmt(f),
1243 ScalarValue::Bool(value) => value.fmt(f),
1244 ScalarValue::C32(value) => value.fmt(f),
1245 ScalarValue::C64(value) => value.fmt(f),
1246 }
1247 }
1248}
1249
1250impl fmt::Debug for BackendScalar {
1251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1252 f.debug_struct("BackendScalar")
1253 .field("dtype", &self.native.dtype())
1254 .field("value", &self.value())
1255 .finish()
1256 }
1257}
1258
1259impl Clone for BackendScalar {
1260 fn clone(&self) -> Self {
1261 match self.value {
1262 ScalarValue::F32(value) => Self::from_value(value),
1263 ScalarValue::F64(value) => Self::from_value(value),
1264 ScalarValue::I32(value) => Self::from_i32(value),
1265 ScalarValue::I64(value) => Self::from_i64(value),
1266 ScalarValue::Bool(value) => Self::from_bool(value),
1267 ScalarValue::C32(value) => Self::from_value(value),
1268 ScalarValue::C64(value) => Self::from_value(value),
1269 }
1270 }
1271}
1272
1273#[cfg(test)]
1274mod tests;