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    sql_example = r#"```sql
36> SELECT cot(1);
37+---------+
38| cot(1)  |
39+---------+
40| 0.64209 |
41+---------+
42```"#,
43    standard_argument(name = "numeric_expression", prefix = "Numeric")
44)]
45#[derive(Debug, PartialEq, Eq, Hash)]
46pub struct CotFunc {
47    signature: Signature,
48}
49
50impl Default for CotFunc {
51    fn default() -> Self {
52        CotFunc::new()
53    }
54}
55
56impl CotFunc {
57    pub fn new() -> Self {
58        use DataType::*;
59        Self {
60            // math expressions expect 1 argument of type f64 or f32
61            // priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we
62            // return the best approximation for it (in f64).
63            // We accept f32 because in this case it is clear that the best approximation
64            // will be as good as the number of digits in the number
65            signature: Signature::uniform(
66                1,
67                vec![Float64, Float32],
68                Volatility::Immutable,
69            ),
70        }
71    }
72}
73
74impl ScalarUDFImpl for CotFunc {
75    fn as_any(&self) -> &dyn Any {
76        self
77    }
78
79    fn name(&self) -> &str {
80        "cot"
81    }
82
83    fn signature(&self) -> &Signature {
84        &self.signature
85    }
86
87    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
88        match arg_types[0] {
89            Float32 => Ok(Float32),
90            _ => Ok(Float64),
91        }
92    }
93
94    fn documentation(&self) -> Option<&Documentation> {
95        self.doc()
96    }
97
98    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
99        make_scalar_function(cot, vec![])(&args.args)
100    }
101}
102
103///cot SQL function
104fn cot(args: &[ArrayRef]) -> Result<ArrayRef> {
105    match args[0].data_type() {
106        Float64 => Ok(Arc::new(
107            args[0]
108                .as_primitive::<Float64Type>()
109                .unary::<_, Float64Type>(|x: f64| compute_cot64(x)),
110        ) as ArrayRef),
111        Float32 => Ok(Arc::new(
112            args[0]
113                .as_primitive::<Float32Type>()
114                .unary::<_, Float32Type>(|x: f32| compute_cot32(x)),
115        ) as ArrayRef),
116        other => exec_err!("Unsupported data type {other:?} for function cot"),
117    }
118}
119
120fn compute_cot32(x: f32) -> f32 {
121    let a = f32::tan(x);
122    1.0 / a
123}
124
125fn compute_cot64(x: f64) -> f64 {
126    let a = f64::tan(x);
127    1.0 / a
128}
129
130#[cfg(test)]
131mod test {
132    use crate::math::cot::cot;
133    use arrow::array::{ArrayRef, Float32Array, Float64Array};
134    use datafusion_common::cast::{as_float32_array, as_float64_array};
135    use std::sync::Arc;
136
137    #[test]
138    fn test_cot_f32() {
139        let args: Vec<ArrayRef> =
140            vec![Arc::new(Float32Array::from(vec![12.1, 30.0, 90.0, -30.0]))];
141        let result = cot(&args).expect("failed to initialize function cot");
142        let floats =
143            as_float32_array(&result).expect("failed to initialize function cot");
144
145        let expected = Float32Array::from(vec![
146            -1.986_460_4,
147            -0.156_119_96,
148            -0.501_202_8,
149            0.156_119_96,
150        ]);
151
152        let eps = 1e-6;
153        assert_eq!(floats.len(), 4);
154        assert!((floats.value(0) - expected.value(0)).abs() < eps);
155        assert!((floats.value(1) - expected.value(1)).abs() < eps);
156        assert!((floats.value(2) - expected.value(2)).abs() < eps);
157        assert!((floats.value(3) - expected.value(3)).abs() < eps);
158    }
159
160    #[test]
161    fn test_cot_f64() {
162        let args: Vec<ArrayRef> =
163            vec![Arc::new(Float64Array::from(vec![12.1, 30.0, 90.0, -30.0]))];
164        let result = cot(&args).expect("failed to initialize function cot");
165        let floats =
166            as_float64_array(&result).expect("failed to initialize function cot");
167
168        let expected = Float64Array::from(vec![
169            -1.986_458_685_881_4,
170            -0.156_119_952_161_6,
171            -0.501_202_783_380_1,
172            0.156_119_952_161_6,
173        ]);
174
175        let eps = 1e-12;
176        assert_eq!(floats.len(), 4);
177        assert!((floats.value(0) - expected.value(0)).abs() < eps);
178        assert!((floats.value(1) - expected.value(1)).abs() < eps);
179        assert!((floats.value(2) - expected.value(2)).abs() < eps);
180        assert!((floats.value(3) - expected.value(3)).abs() < eps);
181    }
182}