COS(number) returns the cosine of an angle given in radians: COS(PI()/4) is 0.7071. DuckDB, Snowflake and BigQuery spell it cos() too. If your angles are in degrees, convert first with RADIANS(). Watch where the aggregate sits: AVG(COS(x)) and COS(AVG(x)) are different numbers.
Updated · Checked on the xmetric engine
What is the syntax?
COS(number)
number
an angle in radians. Use RADIANS([Degrees]) for angles in degrees.
Returns a number from -1 to 1. Null if the input is null.
What does it return, and what is the SQL?
Each example runs on the same 8 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
What is the cosine of each angle?
Tableau
COS([Value])
SQL (DuckDB)
SELECTcos(Value) AS result
FROM input
ORDERBY id
Value is read as radians: 0 gives 1, 16 radians gives -0.958.
Value
Result
2.5
−0.8
−2.5
−0.8
0.13
0.99
−0.4
0.92
3.75
−0.82
null
0
1
16
−0.96
✓ The Tableau formula and the SQL return the same 8 rows.
What is the average cosine per region?
Tableau
AVG(COS([Value]))
SQL (DuckDB)
SELECT Region, avg(cos(Value)) AS result
FROM input
GROUPBY Region
ORDERBY Region
Each row's cosine is taken first, then averaged per region; the null row is skipped.
Region
Result
East
−0.2
North
0.02
West
0.05
✓ The Tableau formula and the SQL return the same 3 rows.
Where does a straight translation go wrong?
Common mistake
Why is cos(avg(x)) not the same as avg(cos(x))?
Averaging the angles first gives the cosine of one middle angle. Tableau's formula takes the cosine of each row and then averages, so East is -0.20 in Tableau and 1.00 in the SQL. Keep the order of the formula.
Tableau
AVG(COS([Value]))
Tempting SQL
SELECT Region, cos(avg(Value)) AS result
FROM input
GROUPBY Region
ORDERBY Region
SQL that matches
SELECT Region, avg(cos(Value)) AS result
FROM input
GROUPBY Region
ORDERBY Region
Region
Tableau
Tempting SQL
SQL that matches
East
−0.2
1
−0.2
North
0.02
−0.15
0.02
West
0.05
−0.1
0.05
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
How do I write it in Snowflake or BigQuery?
The first example, written for each warehouse from its documentation. These are not run here; DuckDB is.
Radians. For degrees, write COS(RADIANS([Angle])); in SQL, cos(radians(Angle)).
Why average the sine and cosine of angles?
Angles wrap around: the plain average of 350 and 10 degrees is 180, the opposite direction. The mean direction is ATAN2(AVG(SIN(a)), AVG(COS(a))), which needs the trigonometry inside the average.