Skip to main content

datafusion_common/
float_semantics.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Float semantics for DataFusion.
6//!
7//! Arrow's comparison kernels work on the bit pattern of a float,
8//! i.e. IEEE 754 totalOrder. DataFusion deviates from that in one
9//! respect: `+0.0` and `-0.0` are equal, hash the same and fall into the same
10//! group. See [`normalize_float`], [`normalize_floats`] and
11//! [`ScalarValue::normalize`]. Ordering still follows totalOrder, so
12//! [`compare_floats`] sorts `-0.0` before `+0.0`.
13//!
14//! Every comparison, hash or grouping boundary should be built from these
15//! helpers rather than inspecting float bits itself:
16//!
17//! - Equality and grouping: normalize first ([`normalize_float`],
18//!   [`normalize_floats`], [`ScalarValue::normalize`]), then compare bits or
19//!   call Arrow's `eq`, `RowConverter` or `make_comparator`. Hash
20//!   [`hash_input`].
21//! - Ordering: use [`compare_floats`], [`float_lt`] or [`float_gt`]. Sorting
22//!   does not normalize yet, so `-0.0` still sorts before `+0.0`.
23//!
24//! [`ScalarValue::normalize`]: crate::ScalarValue::normalize
25
26use std::cmp::Ordering;
27use std::sync::Arc;
28
29use arrow::array::{Array, ArrayRef, AsArray, make_array};
30use arrow::datatypes::{
31    ArrowPrimitiveType, DataType, Float16Type, Float32Type, Float64Type,
32};
33use half::f16;
34
35/// The floating point types the functions in this module are defined for:
36/// [`f16`](struct@f16), [`f32`] and [`f64`].
37pub trait FloatSemantics: Copy {
38    /// Whether [`normalize_float`] would change this value. This is a cheap
39    /// check that lets callers skip rewriting data which is already
40    /// normalized.
41    fn needs_normalization(self) -> bool;
42
43    /// See [`normalize_float`].
44    fn normalize(self) -> Self;
45
46    /// See [`compare_floats`].
47    fn compare(self, other: Self) -> Ordering;
48}
49
50macro_rules! impl_float_semantics {
51    ($(($t:ty, $bits:ty, $zero:expr)),+ $(,)?) => {
52        $(impl FloatSemantics for $t {
53            #[inline]
54            fn needs_normalization(self) -> bool {
55                // `-0.0` has only the sign bit set; no other value shares
56                // this bit pattern.
57                self.to_bits() == 1 << (<$bits>::BITS - 1)
58            }
59
60            #[inline]
61            fn normalize(self) -> Self {
62                if self.needs_normalization() { $zero } else { self }
63            }
64
65            #[inline]
66            fn compare(self, other: Self) -> Ordering {
67                self.total_cmp(&other)
68            }
69        })+
70    };
71}
72impl_float_semantics!((f16, u16, f16::ZERO), (f32, u32, 0.0), (f64, u64, 0.0));
73
74/// `-0.0` becomes `0.0`, so two values that DataFusion treats as equal also
75/// have the same bits. All other values, including NaN payloads, are kept as
76/// they are.
77#[inline]
78pub fn normalize_float<T: FloatSemantics>(v: T) -> T {
79    v.normalize()
80}
81
82/// Compares two values in the order DataFusion sorts them.
83///
84/// This is IEEE 754 totalOrder (`total_cmp`), which matches Arrow's sort
85/// kernels and row encoding. Note that it orders `-0.0` before `+0.0`.
86/// The grouped `MIN`/`MAX` accumulators start from the extremes of this
87/// order, so they must change together with it.
88#[inline]
89pub fn compare_floats<T: FloatSemantics>(left: T, right: T) -> Ordering {
90    left.compare(right)
91}
92
93/// Whether `left` sorts before `right`, the same as
94/// `compare_floats(left, right).is_lt()`.
95#[inline]
96pub fn float_lt<T: FloatSemantics>(left: T, right: T) -> bool {
97    compare_floats(left, right).is_lt()
98}
99
100/// Whether `left` sorts after `right`, the same as
101/// `compare_floats(left, right).is_gt()`.
102#[inline]
103pub fn float_gt<T: FloatSemantics>(left: T, right: T) -> bool {
104    compare_floats(left, right).is_gt()
105}
106
107/// The value that DataFusion hashes in place of a float. Values that DataFusion
108/// treats as equal hash the same, so this is the value [`normalize_float`]
109/// returns.
110#[inline]
111pub fn hash_input<T: FloatSemantics>(v: T) -> T {
112    normalize_float(v)
113}
114
115/// Applies [`normalize_float`] to every float in `array`, including floats
116/// nested inside lists, structs, maps, unions, dictionaries and run-end
117/// encoded arrays. Arrays without floats are returned unchanged.
118///
119/// Callers use this before handing float data to Arrow kernels that compare
120/// bit patterns, so that `+0.0 = -0.0` holds.
121///
122/// The common case - nothing to normalize - is allocation-free: a single
123/// read-only scan of the values buffer (auto-vectorizable to an OR-reduction)
124/// decides whether to fall through to the rewriting path. Only arrays that
125/// contain values to normalize pay for a new buffer.
126pub fn normalize_floats(array: &ArrayRef) -> ArrayRef {
127    match array.data_type() {
128        DataType::Float16 => normalize_primitive::<Float16Type>(array),
129        DataType::Float32 => normalize_primitive::<Float32Type>(array),
130        DataType::Float64 => normalize_primitive::<Float64Type>(array),
131        dt if has_float_leaf(dt) => {
132            let data = array.to_data();
133            let children = data
134                .child_data()
135                .iter()
136                .map(|child| normalize_floats(&make_array(child.clone())).to_data())
137                .collect::<Vec<_>>();
138            if children
139                .iter()
140                .zip(data.child_data())
141                .all(|(new, old)| new.ptr_eq(old))
142            {
143                return Arc::clone(array);
144            }
145            make_array(
146                data.into_builder()
147                    .child_data(children)
148                    .build()
149                    .expect("rewriting float leaves preserves the array layout"),
150            )
151        }
152        _ => Arc::clone(array),
153    }
154}
155
156fn normalize_primitive<T>(array: &ArrayRef) -> ArrayRef
157where
158    T: ArrowPrimitiveType,
159    T::Native: FloatSemantics,
160{
161    let arr = array.as_primitive::<T>();
162    if !arr.values().iter().any(|v| v.needs_normalization()) {
163        return Arc::clone(array);
164    }
165    Arc::new(arr.unary::<_, T>(normalize_float))
166}
167
168/// Whether `data_type` is a float or contains a float at any depth of its
169/// nested children.
170pub fn has_float_leaf(data_type: &DataType) -> bool {
171    match data_type {
172        DataType::Float16 | DataType::Float32 | DataType::Float64 => true,
173        DataType::List(f)
174        | DataType::LargeList(f)
175        | DataType::ListView(f)
176        | DataType::LargeListView(f)
177        | DataType::FixedSizeList(f, _)
178        | DataType::Map(f, _)
179        | DataType::RunEndEncoded(_, f) => has_float_leaf(f.data_type()),
180        DataType::Struct(fields) => fields.iter().any(|f| has_float_leaf(f.data_type())),
181        DataType::Union(fields, _) => {
182            fields.iter().any(|(_, f)| has_float_leaf(f.data_type()))
183        }
184        DataType::Dictionary(_, values) => has_float_leaf(values),
185        _ => false,
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use crate::{Result, ScalarValue};
193    use arrow::array::{
194        DictionaryArray, Float16Array, Float32Array, Float64Array, Int8Array, Int32Array,
195        ListArray,
196    };
197    use arrow::datatypes::{Field, Int8Type, Int32Type};
198
199    #[test]
200    fn normalize_float_folds_negative_zero() {
201        assert_eq!(normalize_float(-0.0_f64).to_bits(), 0.0_f64.to_bits());
202        assert_eq!(normalize_float(-0.0_f32).to_bits(), 0.0_f32.to_bits());
203        assert_eq!(
204            normalize_float(f16::NEG_ZERO).to_bits(),
205            f16::ZERO.to_bits()
206        );
207        assert_eq!(
208            hash_input(-0.0_f64).to_bits(),
209            hash_input(0.0_f64).to_bits()
210        );
211        assert!((-0.0_f64).needs_normalization());
212        assert!(!0.0_f64.needs_normalization());
213    }
214
215    #[test]
216    fn normalize_float_keeps_other_values() {
217        let neg_nan = f64::from_bits(f64::NAN.to_bits() | (1 << 63));
218        let payload_nan = f64::from_bits(f64::NAN.to_bits() | 1);
219        for v in [
220            1.5,
221            -1.5,
222            f64::INFINITY,
223            f64::NEG_INFINITY,
224            f64::MIN_POSITIVE,
225            -f64::MIN_POSITIVE,
226            f64::NAN,
227            neg_nan,
228            payload_nan,
229        ] {
230            assert!(!v.needs_normalization());
231            assert_eq!(normalize_float(v).to_bits(), v.to_bits());
232        }
233    }
234
235    #[test]
236    fn compare_floats_is_total_order() {
237        let neg_nan = f64::from_bits(f64::NAN.to_bits() | (1 << 63));
238        assert_eq!(compare_floats(1.0_f64, 2.0), Ordering::Less);
239        assert_eq!(compare_floats(-0.0_f64, 0.0), Ordering::Less);
240        assert_eq!(compare_floats(f64::NAN, f64::INFINITY), Ordering::Greater);
241        assert_eq!(compare_floats(neg_nan, f64::NEG_INFINITY), Ordering::Less);
242        assert_eq!(compare_floats(f16::ONE, f16::ZERO), Ordering::Greater);
243        assert!(float_lt(1.0_f64, 2.0) && !float_lt(2.0_f64, 1.0));
244        assert!(float_gt(f64::NAN, f64::INFINITY) && !float_gt(1.0_f64, 1.0));
245    }
246
247    #[test]
248    fn normalize_floats_rewrites_negative_zero() {
249        let array: ArrayRef =
250            Arc::new(Float64Array::from(vec![Some(-0.0), None, Some(1.0)]));
251        let result = normalize_floats(&array);
252        let result = result.as_primitive::<Float64Type>();
253        assert_eq!(result.value(0).to_bits(), 0.0_f64.to_bits());
254        assert!(result.is_null(1));
255        assert_eq!(result.value(2), 1.0);
256
257        let array: ArrayRef = Arc::new(Float32Array::from(vec![-0.0_f32]));
258        let result = normalize_floats(&array);
259        assert_eq!(
260            result.as_primitive::<Float32Type>().value(0).to_bits(),
261            0.0_f32.to_bits()
262        );
263
264        let array: ArrayRef = Arc::new(Float16Array::from(vec![f16::NEG_ZERO]));
265        let result = normalize_floats(&array);
266        assert_eq!(
267            result.as_primitive::<Float16Type>().value(0).to_bits(),
268            f16::ZERO.to_bits()
269        );
270    }
271
272    #[test]
273    fn normalize_floats_reuses_normalized_input() {
274        let array: ArrayRef = Arc::new(Float64Array::from(vec![0.0, 1.0, f64::NAN]));
275        assert!(Arc::ptr_eq(&normalize_floats(&array), &array));
276
277        let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2]));
278        assert!(Arc::ptr_eq(&normalize_floats(&array), &array));
279    }
280
281    #[test]
282    fn normalize_floats_rewrites_nested_floats() {
283        let list = ListArray::from_iter_primitive::<Float64Type, _, _>(vec![
284            Some(vec![Some(-0.0), Some(2.0)]),
285            None,
286        ]);
287        let array: ArrayRef = Arc::new(list);
288        let result = normalize_floats(&array);
289        assert!(!Arc::ptr_eq(&result, &array));
290        let values = result.as_list::<i32>().value(0);
291        assert_eq!(
292            values.as_primitive::<Float64Type>().value(0).to_bits(),
293            0.0_f64.to_bits()
294        );
295        assert!(result.is_null(1));
296
297        let list =
298            ListArray::from_iter_primitive::<Int32Type, _, _>(vec![Some(vec![Some(1)])]);
299        let array: ArrayRef = Arc::new(list);
300        assert!(Arc::ptr_eq(&normalize_floats(&array), &array));
301    }
302
303    #[test]
304    fn normalize_floats_in_dictionary_arrays_and_scalars() -> Result<()> {
305        let nan = f64::from_bits(0x7ff8_0000_0000_0001);
306        let keys = Int8Array::from(vec![Some(0), Some(1), None, Some(2)]);
307        let array: ArrayRef = Arc::new(DictionaryArray::try_new(
308            keys.clone(),
309            Arc::new(Float64Array::from(vec![-0.0, nan, 1.0])),
310        )?);
311
312        let normalized = normalize_floats(&array);
313        let dictionary = normalized.as_dictionary::<Int8Type>();
314        assert_eq!(dictionary.keys(), &keys);
315        let values = dictionary.values().as_primitive::<Float64Type>();
316        assert_eq!(values.value(0).to_bits(), 0.0_f64.to_bits());
317        assert_eq!(values.value(1).to_bits(), nan.to_bits());
318        assert_eq!(values.value(2), 1.0);
319
320        assert!(Arc::ptr_eq(&normalize_floats(&normalized), &normalized));
321
322        assert_eq!(
323            ScalarValue::try_from_array(&array, 0)?.normalize(),
324            ScalarValue::try_from_array(&normalized, 0)?
325        );
326
327        Ok(())
328    }
329
330    #[test]
331    fn normalize_preserves_union_and_run_metadata() -> Result<()> {
332        use arrow::datatypes::{UnionFields, UnionMode};
333
334        let run_ends = Arc::new(Field::new("ends", DataType::Int32, false));
335        let values = Arc::new(Field::new("samples", DataType::Float64, true));
336        let fields = UnionFields::try_new(
337            [7, 42],
338            [
339                Field::new(
340                    "runs",
341                    DataType::RunEndEncoded(Arc::clone(&run_ends), Arc::clone(&values)),
342                    true,
343                ),
344                Field::new("other", DataType::Int32, true),
345            ],
346        )?;
347        let nan = f64::from_bits(0x7ff8_0000_0000_0001);
348        for mode in [UnionMode::Sparse, UnionMode::Dense] {
349            let wrap = |value| {
350                ScalarValue::Union(
351                    Some((
352                        7,
353                        Box::new(ScalarValue::RunEndEncoded(
354                            Arc::clone(&run_ends),
355                            Arc::clone(&values),
356                            Box::new(ScalarValue::Float64(value)),
357                        )),
358                    )),
359                    fields.clone(),
360                    mode,
361                )
362            };
363            for (value, expected) in [
364                (Some(-0.0), Some(0.0)),
365                (Some(nan), Some(nan)),
366                (None, None),
367            ] {
368                assert_eq!(wrap(value).normalize(), wrap(expected));
369            }
370            let null = ScalarValue::Union(None, fields.clone(), mode);
371            assert_eq!(null.clone().normalize(), null);
372        }
373        Ok(())
374    }
375
376    #[test]
377    fn normalize_preserves_sliced_list() {
378        let nan = f64::from_bits(0x7ff8_0000_0000_0001);
379        let list = Arc::new(
380            ListArray::from_iter_primitive::<Float64Type, _, _>([
381                Some(vec![Some(99.0)]),
382                Some(vec![Some(-0.0), Some(nan), None]),
383                Some(vec![Some(42.0)]),
384            ])
385            .slice(1, 1),
386        );
387        let ScalarValue::List(normalized) = ScalarValue::List(list).normalize() else {
388            panic!("normalization must preserve the scalar variant");
389        };
390        assert_eq!(normalized.len(), 1);
391        let child = normalized.value(0);
392        let child = child.as_primitive::<Float64Type>();
393        assert_eq!(child.len(), 3);
394        assert_eq!(child.value(0).to_bits(), 0.0_f64.to_bits());
395        assert_eq!(child.value(1).to_bits(), nan.to_bits());
396        assert!(child.is_null(2));
397    }
398}