Skip to content

Apache DataFusion SQL Query Engine

ARROW-9891: [Rust] [DataFusion] Made math functions accept f32.

Jorge C. Leitaoa4eb8fd56bc8
diff --git a/rust/datafusion/src/physical_plan/functions.rs b/rust/datafusion/src/physical_plan/functions.rs
index ce617c7bb0..1a9e2062f2 100644
--- a/rust/datafusion/src/physical_plan/functions.rs
+++ b/rust/datafusion/src/physical_plan/functions.rs
@@ -206,8 +206,12 @@ fn signature(fun: &ScalarFunction) -> Signature {
// for now, the list is small, as we do not have many built-in functions.
match fun {
ScalarFunction::Length => Signature::Uniform(1, vec![DataType::Utf8]),
- // math expressions expect 1 argument of type f64
- _ => Signature::Uniform(1, vec![DataType::Float64]),
+ // math expressions expect 1 argument of type f64 or f32
+ // priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we
+ // return the best approximation for it (in f64).
+ // We accept f32 because in this case it is clear that the best approximation
+ // will be as good as the number of digits in the number
+ _ => Signature::Uniform(1, vec![DataType::Float64, DataType::Float32]),
}
}
@@ -243,18 +247,21 @@ mod tests {
let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
// value is correct
- assert_eq!(format!("{}", result.value(0)), expected); // = exp(1)
+ assert_eq!(format!("{}", result.value(0)), expected);
Ok(())
}
#[test]
fn test_math_function() -> Result<()> {
+ // 2.71828182845904523536... : https://oeis.org/A001113
let exp_f64 = "2.718281828459045";
+ let exp_f32 = "2.7182817459106445";
generic_test_math(ScalarValue::Int32(1i32), exp_f64)?;
generic_test_math(ScalarValue::UInt32(1u32), exp_f64)?;
+ generic_test_math(ScalarValue::UInt64(1u64), exp_f64)?;
generic_test_math(ScalarValue::Float64(1f64), exp_f64)?;
- generic_test_math(ScalarValue::Float32(1f32), exp_f64)?;
+ generic_test_math(ScalarValue::Float32(1f32), exp_f32)?;
Ok(())
}
}
diff --git a/rust/datafusion/src/physical_plan/math_expressions.rs b/rust/datafusion/src/physical_plan/math_expressions.rs
index 7ea0795bb7..aad1958d5c 100644
--- a/rust/datafusion/src/physical_plan/math_expressions.rs
+++ b/rust/datafusion/src/physical_plan/math_expressions.rs
@@ -19,32 +19,57 @@
use crate::error::{ExecutionError, Result};
-use arrow::array::{Array, ArrayRef, Float64Array, Float64Builder};
+use arrow::array::{Array, ArrayRef, Float32Array, Float64Array, Float64Builder};
+
+use arrow::datatypes::DataType;
use std::sync::Arc;
+macro_rules! compute_op {
+ ($ARRAY:expr, $FUNC:ident, $TYPE:ident) => {{
+ let mut builder = Float64Builder::new($ARRAY.len());
+ for i in 0..$ARRAY.len() {
+ if $ARRAY.is_null(i) {
+ builder.append_null()?;
+ } else {
+ builder.append_value($ARRAY.value(i).$FUNC() as f64)?;
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ }};
+}
+
+macro_rules! downcast_compute_op {
+ ($ARRAY:expr, $NAME:expr, $FUNC:ident, $TYPE:ident) => {{
+ let n = $ARRAY.as_any().downcast_ref::<$TYPE>();
+ match n {
+ Some(array) => compute_op!(array, $FUNC, $TYPE),
+ _ => Err(ExecutionError::General(format!(
+ "Invalid data type for {}",
+ $NAME
+ ))),
+ }
+ }};
+}
+
+macro_rules! unary_primitive_array_op {
+ ($ARRAY:expr, $NAME:expr, $FUNC:ident) => {{
+ match ($ARRAY).data_type() {
+ DataType::Float32 => downcast_compute_op!($ARRAY, $NAME, $FUNC, Float32Array),
+ DataType::Float64 => downcast_compute_op!($ARRAY, $NAME, $FUNC, Float64Array),
+ other => Err(ExecutionError::General(format!(
+ "Unsupported data type {:?} for function {}",
+ other, $NAME,
+ ))),
+ }
+ }};
+}
+
macro_rules! math_unary_function {
($NAME:expr, $FUNC:ident) => {
- /// mathematical function
+ /// mathematical function that accepts f32 or f64 and returns f64
pub fn $FUNC(args: &[ArrayRef]) -> Result<ArrayRef> {
- let n = &args[0].as_any().downcast_ref::<Float64Array>();
- match n {
- Some(array) => {
- let mut builder = Float64Builder::new(array.len());
- for i in 0..array.len() {
- if array.is_null(i) {
- builder.append_null()?;
- } else {
- builder.append_value(array.value(i).$FUNC())?;
- }
- }
- Ok(Arc::new(builder.finish()))
- }
- _ => Err(ExecutionError::General(format!(
- "Invalid data type for {}",
- $NAME
- ))),
- }
+ unary_primitive_array_op!(args[0], $NAME, $FUNC)
}
};
}
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index f1119969f1..345ab894f7 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -201,16 +201,21 @@ fn csv_query_avg_sqrt() -> Result<()> {
Ok(())
}
+/// sqrt(f32) is sligthly different than sqrt(CAST(f32 AS double)))
#[test]
-fn csv_query_sqrt_f32() -> Result<()> {
+fn sqrt_f32_vs_f64() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
// sqrt(f32)'s plan passes
let sql = "SELECT avg(sqrt(c11)) FROM aggregate_test_100";
- let mut actual = execute(&mut ctx, sql);
- actual.sort();
+ let actual = &execute(&mut ctx, sql)[0];
+ let expected = "0.6584408485889435".to_string();
+
+ assert_eq!(*actual, expected);
+ let sql = "SELECT avg(sqrt(CAST(c11 AS double))) FROM aggregate_test_100";
+ let actual = &execute(&mut ctx, sql)[0];
let expected = "0.6584408483418833".to_string();
- assert_eq!(actual.join("\n"), expected);
+ assert_eq!(*actual, expected);
Ok(())
}