haversine()#

relationalai.std.math
#haversine(x1: Number|Producer, y1: Number|Producer, x2: Number|Producer, y2: Number|Producer, radius: Number|Producer = 1.0) -> Expression

Calculates the haversine distance between two points specified by their coordinates (x1, y1) and (x2, y2), on a sphere with the given radius. If any of the inputs are a Producer, haversine() filters out any non-numeric values from the producer. Must be called in a rule or query context.

Parameters#

NameTypeDescription
x1Producer or Python Number objectThe x-coordinate of the first point.
y1Producer or Python Number objectThe y-coordinate of the first point.
x2Producer or Python Number objectThe x-coordinate of the second point.
y2Producer or Python Number objectThe y-coordinate of the second point.
radiusProducer or Python Number objectThe radius of the sphere. (Default: 1.0).

Returns#

An Expression object.

Example#

Use haversine() to calculate the distance between points on a sphere with a given radius:

#import relationalai as rai
from relationalai.std import math


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

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

with model.rule():
    Location.add(id=1).set(name="LocationA", x=0, y=0)
    Location.add(id=2).set(name="LocationB", x=3.14159 / 2, y=3.14159 / 2)  # Approximately π/2
    Location.add(id=3).set(name="LocationC", x="INVALID", y=0)  # Non-numeric value


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

# Set a distance property to the haversine distance from LocationA to each other
# location, assuming a unit sphere.
with model.rule():
    loc1 = Location(id=1)  # Reference location
    loc2 = Location()
    loc2.set(distance_from_A=math.haversine(loc1.x, loc1.y, loc2.x, loc2.y))

# Since haversine() filters out non-numeric values, the distance_from_A property
# is not set for LocationC.
with model.query() as select:
    loc = Location()
    response = select(loc.name, loc.distance_from_A)

print(response.results)
#         name  distance_from_a
# 0  LocationA         0.000000
# 1  LocationB         1.570796
# 2  LocationC              NaN

See Also#