Applies to VAST Cluster 5.5.
Functions › Numeric and math functions › Hyperbolic functions. Returns the hyperbolic tangent of a number, sinh(x) / cosh(x). It takes any number and returns a value from -1 to 1, which makes it a smooth way to squash an unbounded score into that range.
Syntax
tanh(x)
| Argument | Type | Description |
|---|---|---|
x |
Any number (DOUBLE, REAL, an integer or a DECIMAL) |
Any value, including inf and -inf. |
Returns: DOUBLE, from -1 to 1.
Set up the examples
The examples connect with the ADBC driver, as in VAST Query Engine (ADBC), and work in a schema called docs_sql_fn_numeric_tanh. Set QE_ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and VASTDB_BUCKET (SQL reference), and run the blocks in order in one Python session. Below each block is the output you should see.
This block connects, defines the run() and plan() helpers, and creates a table of six raw scores. Row 3 has no score:
import os
import re
import adbc_driver_manager
import adbc_driver_manager.dbapi as dbapi
import adbc_driver_vastdb
BUCKET = os.environ["VASTDB_BUCKET"]
SCHEMA = f'"{BUCKET}/docs_sql_fn_numeric_tanh"'
conn = dbapi.connect(
driver=adbc_driver_vastdb.get_driver_path(),
db_kwargs={
"vast.db.endpoint": os.environ["QE_ENDPOINT"],
"vast.db.access_key": os.environ["AWS_ACCESS_KEY_ID"],
"vast.db.secret_key": os.environ["AWS_SECRET_ACCESS_KEY"],
},
autocommit=True,
)
def server_message(e):
"""The server's message in a driver error, without the request ID or the echoed statement."""
text = re.sub(r"\[req=0x[0-9a-f]+\]: ", "", str(e))
found = (re.search(r'message: "(.*?)", request_id', text, re.S)
or re.search(r"description: (.*)\)", text, re.S))
message = found.group(1) if found else text.strip().splitlines()[-1]
message = re.sub(r"^Plan query: '.*?' failed with: ", "", message, flags=re.S)
message = re.split(r"\\n|\n", message)[0].replace('\\"', '"')
return message.replace(BUCKET, "<bucket>")
def run(sql):
"""Run one statement. Print the rows it returns, or the error."""
try:
with conn.cursor() as cur:
cur.execute(sql)
rows = cur.fetchall() if cur.description else []
except (adbc_driver_manager.Error, OSError) as e:
print(f"{type(e).__name__}: {server_message(e)}")
else:
print(rows)
def plan(sql):
"""Print the plan without its ~N Rows lines: the table's row count, which can still be 0 just after an insert."""
with conn.cursor() as cur:
cur.execute("EXPLAIN " + sql)
steps = cur.fetchall()[0][1]
print("\n".join(line for line in steps.splitlines() if "Rows" not in line))
TABLE = f"{SCHEMA}.scores"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, score DOUBLE)")
run(f"INSERT INTO {TABLE} VALUES "
"(1, 0.5), (2, -1.0), (3, NULL), (4, 0.0), (5, 3.0), (6, 25.0)")
[]
[]
[(6,)]
What it does
tanh(x) is the hyperbolic tangent, sinh(x) / cosh(x). It's an odd function (tanh(-x) is -tanh(x)), it's 0 at 0, and it approaches 1 as x grows and -1 as x falls. Its inverse is atanh.
| Call | Result |
|---|---|
tanh(0) |
0.0 |
tanh(1) |
0.7615941559557649 |
tanh(20) |
1.0: the nearest DOUBLE to the true value |
tanh(-20) |
-1.0 |
tanh(1e308) |
1.0 |
The result is a DOUBLE for every numeric argument type: an integer, a REAL, a DECIMAL or a DOUBLE.
run("SELECT tanh(0), tanh(1), tanh(20), tanh(-20), tanh(1e308)")
run("SELECT typeof(tanh(1::INTEGER)), typeof(tanh(0.5::FLOAT)), typeof(tanh(0.5))")
[(0.0, 0.7615941559557649, 1.0, -1.0, 1.0)]
[('DOUBLE', 'DOUBLE', 'DOUBLE')]
NULLs and edge cases
| Input | Result |
|---|---|
NULL |
NULL |
'inf'::DOUBLE |
1.0 |
'-inf'::DOUBLE |
-1.0 |
'nan'::DOUBLE |
nan |
-0.0::DOUBLE |
-0.0: the sign of zero is kept |
The smallest positive DOUBLE (5e-324) |
5e-324 |
'12' (a string literal holding a number) |
Converted to DOUBLE: 0.9999999999244973 |
'abc' (a string that isn't a number) |
Error: Could not convert string 'abc' to DOUBLE |
A BLOB, date, boolean, list or interval |
Error: No function matches the given name and argument types, for example 'tanh(DATE)' |
The same cases, as the cluster returns them. They use the helpers from Set up the examples:
run("SELECT tanh(NULL), tanh('inf'::DOUBLE), tanh('-inf'::DOUBLE), tanh('nan'::DOUBLE)")
run("SELECT tanh(-0.0::DOUBLE), tanh(5e-324::DOUBLE), tanh('12')")
run("SELECT tanh('abc')")
run("SELECT tanh(DATE '2026-10-16')")
[(None, 1.0, -1.0, nan)]
[(-0.0, 5e-324, 0.9999999999244973)]
OSError: Could not convert string 'abc' to DOUBLE
InternalError: Binder Error: No function matches the given name and argument types 'tanh(DATE)'. You might need to add explicit type casts.
Examples
Each raw score squashed into the range -1 to 1, and the same squash with the score scaled first, which keeps more of the difference between large scores:
run(f"SELECT id, score, tanh(score), tanh(score / 10) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, 0.5, 0.46211715726000974, 0.04995837495787998), (2, -1.0, -0.7615941559557649, -0.09966799462495582), (3, None, None, None), (4, 0.0, 0.0, 0.0), (5, 3.0, 0.9950547536867305, 0.2913126124515909), (6, 25.0, 1.0, 0.9866142981514303)]
Keep only the rows whose squashed score is above 0.9:
run(f"SELECT id, score FROM {TABLE} WHERE tanh(score) > 0.9 ORDER BY id LIMIT 10")
[(5, 3.0), (6, 25.0)]
How it runs in VAST
The Query Engine runs on the cluster's CNodes, and a query on a table starts with a scan in VAST DataBase (VAST_SCAN). VAST DataBase can evaluate a comparison of a column with a constant, but not a function of a column, so tanh() is always computed by the Query Engine:
- In the
SELECTlist, the scan reads the column and the Query Engine computestanh()for each row it returns. - In
WHERE, the scan sends the column for every row, and aFILTERstep in the Query Engine computestanh()and keeps the rows that match. No rows are skipped in storage.
The plan of the WHERE example shows the FILTER step above the scan:
plan(f"SELECT id FROM {TABLE} WHERE tanh(score) > 0.9")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ (tanh(score) > 0.9) │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ │
│ Projections: │
│ score │
│ id │
│ │
└───────────────────────────┘
Make it faster
- Compare the raw column with the inverse of the constant.
tanh()grows as its argument grows, sotanh(score) > 0.9is the same condition asscore > atanh(0.9). A function on constants is computed once, before the scan, so the second form is a comparison of the column with a constant, which is pushed down to VAST DataBase. Its plan has noFILTERstep. The bound must be between -1 and 1:atanh(1)is infinity.
plan(f"SELECT id FROM {TABLE} WHERE score > atanh(0.9)")
run(f"SELECT id, score FROM {TABLE} WHERE score > atanh(0.9) ORDER BY id LIMIT 10")
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
[(5, 3.0), (6, 25.0)]
- Store the result if you filter on it often. Compute it when you write the rows and keep it in its own column: a condition on that column is pushed down, a condition on
tanh()isn't.
Limitations and errors
- Large inputs all give 1. From about 20 up,
tanh()returns exactly1.0(and-1.0from about -20 down), so those values can't be told apart or ordered by theirtanh. Scale the input down first, as intanh(score / 10), or compare the raw column. - Numbers only. A
BLOB, a date, a boolean, a list or an interval fails withNo function matches the given name and argument types; the error lists the one formtanhhas,tanh(DOUBLE) -> DOUBLE. A string literal is converted toDOUBLEif it holds a number, and otherwise fails withCould not convert string 'abc' to DOUBLE. - One argument.
tanh(1, 2)fails withNo function matches the given name and argument types 'tanh(INTEGER_LITERAL, INTEGER_LITERAL)'.
Similar functions
| Function | Returns | Result for 1 |
|---|---|---|
tanh(x) |
the hyperbolic tangent, from -1 to 1 | 0.7615941559557649 |
| sinh | the hyperbolic sine | 1.1752011936438014 |
| cosh | the hyperbolic cosine | 1.5430806348152437 |
| atanh | the inverse of tanh, for -1 to 1 |
atanh(tanh(1)) is 0.9999999999999999 |
| tan | the tangent of an angle in radians | |
| atan | another S-shaped curve, from -pi/2 to pi/2 |
run("SELECT tanh(1), sinh(1), cosh(1), atanh(tanh(1)), sinh(1) / cosh(1), tan(1), atan(1)")
[(0.7615941559557649, 1.1752011936438014, 1.5430806348152437, 0.9999999999999999, 0.7615941559557649, 1.5574077246549023, 0.7853981633974483)]
Clean up:
run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]
See also
- Numeric and math functions: all the numeric functions.
- Where filters run and pushdowns.
- EXPLAIN: how to read a plan.