abs()#

relationalai.std.math
#abs(number: Number|Producer) -> Expression

Calculates the absolute value of a number. If number is a Producer, abs() also acts as a filter and removes non-numeric values from the producer. Must be called in a rule or query context.

Parameters#

NameTypeDescription
numberProducer or Python Number object.The number to calculate the absolute value of.

Returns#

An Expression object.

Example#

Use abs() to calculate the absolute value of a number.

#import relationalai as rai
from relationalai.std import math


# =====
# SETUP
# =====

model = rai.Model("MyModel")
Account = model.Type("Account")

with model.rule():
    Account.add(id=1).set(balance=100.00)
    Account.add(id=2).set(balance=-50.00)
    Account.add(id=3).set(balance="INVALID")  # Non-numeric balance


# =======
# EXAMPLE
# =======

# Set an absolute_balance property to the absolute value of each account's balance.
with model.rule():
    account = Account()
    account.set(absolute_balance=math.abs(account.balance))

# Since abs() filters out non-numeric values, the absolute_balance property isn't
# set for the account with id=3.
with model.query() as select:
    account = Account()
    response = select(account.id, account.absolute_balance)

print(response.results)
#    id  absolute_balance
# 0   1             100.0
# 1   2              50.0
# 2   3               NaN

See Also#