datafusion_functions/math/
cot.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::any::Any;
19use std::sync::Arc;
20
21use arrow::array::{ArrayRef, AsArray};
22use arrow::datatypes::DataType::{Float32, Float64};
23use arrow::datatypes::{DataType, Float32Type, Float64Type};
24
25use crate::utils::make_scalar_function;
26use datafusion_common::{exec_err, Result};
27use datafusion_expr::{ColumnarValue, Documentation, ScalarFunctionArgs};
28use datafusion_expr::{ScalarUDFImpl, Signature, Volatility};
29use datafusion_macros::user_doc;
30
31#[user_doc(
32    doc_section(label = "Math Functions"),
33    description = "Returns the cotangent of a number.",
34    syntax_example = r#"cot(numeric_expression)"#,
35    standard_argument(name = "numeric_expression", prefix = "Numeric")
36)]
37#[derive(Debug)]
38pub struct CotFunc {
39    signature: Signature,
40}
41
42impl Default for CotFunc {
43    fn default() -> Self {
44        CotFunc::new()
45    }
46}
47
48impl CotFunc {
49    pub fn new() -> Self {
50        use DataType::*;
51        Self {
52            // math expressions expect 1 argument of type f64 or f32
53            // priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we
54            // return the best approximation for it (in f64).
55            // We accept f32 because in this case it is clear that the best approximation
56            // will be as good as the number of digits in the number
57            signature: Signature::uniform(
58                1,
59                vec![Float64, Float32],
60                Volatility::Immutable,
61            ),
62        }
63    }
64}
65
66impl ScalarUDFImpl for CotFunc {
67    fn as_any(&self) -> &dyn Any {
68        self
69    }
70
71    fn name(&self) -> &str {
72        "cot"
73    }
74
75    fn signature(&self) -> &Signature {
76        &self.signature
77    }
78
79    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
80        match arg_types[0] {
81            Float32 => Ok(Float32),
82            _ => Ok(Float64),
83        }
84    }
85
86    fn documentation(&self) -> Option<&Documentation> {
87        self.doc()
88    }
89
90    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
91        make_scalar_function(cot, vec![])(&args.args)
92    }
93}
94
95///cot SQL function
96fn cot(args: &[ArrayRef]) -> Result<ArrayRef> {
97    match args[0].data_type() {
98        Float64 => Ok(Arc::new(
99            args[0]
100                .as_primitive::<Float64Type>()
101                .unary::<_, Float64Type>(|x: f64| compute_cot64(x)),
102        ) as ArrayRef),
103        Float32 => Ok(Arc::new(
104            args[0]
105                .as_primitive::<Float32Type>()
106                .unary::<_, Float32Type>(|x: f32| compute_cot32(x)),
107        ) as ArrayRef),
108        other => exec_err!("Unsupported data type {other:?} for function cot"),
109    }
110}
111
112fn compute_cot32(x: f32) -> f32 {
113    let a = f32::tan(x);
114    1.0 / a
115}
116
117fn compute_cot64(x: f64) -> f64 {
118    let a = f64::tan(x);
119    1.0 / a
120}
121
122#[cfg(test)]
123mod test {
124    use crate::math::cot::cot;
125    use arrow::array::{ArrayRef, Float32Array, Float64Array};
126    use datafusion_common::cast::{as_float32_array, as_float64_array};
127    use std::sync::Arc;
128
129    #[test]
130    fn test_cot_f32() {
131        let args: Vec<ArrayRef> =
132            vec![Arc::new(Float32Array::from(vec![12.1, 30.0, 90.0, -30.0]))];
133        let result = cot(&args).expect("failed to initialize function cot");
134        let floats =
135            as_float32_array(&result).expect("failed to initialize function cot");
136
137        let expected = Float32Array::from(vec![
138            -1.986_460_4,
139            -0.156_119_96,
140            -0.501_202_8,
141            0.156_119_96,
142        ]);
143
144        let eps = 1e-6;
145        assert_eq!(floats.len(), 4);
146        assert!((floats.value(0) - expected.value(0)).abs() < eps);
147        assert!((floats.value(1) - expected.value(1)).abs() < eps);
148        assert!((floats.value(2) - expected.value(2)).abs() < eps);
149        assert!((floats.value(3) - expected.value(3)).abs() < eps);
150    }
151
152    #[test]
153    fn test_cot_f64() {
154        let args: Vec<ArrayRef> =
155            vec![Arc::new(Float64Array::from(vec![12.1, 30.0, 90.0, -30.0]))];
156        let result = cot(&args).expect("failed to initialize function cot");
157        let floats =
158            as_float64_array(&result).expect("failed to initialize function cot");
159
160        let expected = Float64Array::from(vec![
161            -1.986_458_685_881_4,
162            -0.156_119_952_161_6,
163            -0.501_202_783_380_1,
164            0.156_119_952_161_6,
165        ]);
166
167        let eps = 1e-12;
168        assert_eq!(floats.len(), 4);
169        assert!((floats.value(0) - expected.value(0)).abs() < eps);
170        assert!((floats.value(1) - expected.value(1)).abs() < eps);
171        assert!((floats.value(2) - expected.value(2)).abs() < eps);
172        assert!((floats.value(3) - expected.value(3)).abs() < eps);
173    }
174}