Skip to content

Bug: Distance is negative #258

Closed
Closed

Description

@alexbarev

Describe the bug

Shouldn't distances for all metrics be non-negative? When I used the Inner Product as a distance measure, I found that it could produce negative values when using Index.search().

The same behavior is observed in the C# binding, so I suspect the same will occur when using the C99 interface.

Steps to reproduce

import numpy as np
from usearch.index import Index, Matches

index = Index(
    ndim=3, 
    metric='ip', 
    dtype='f32', 
)

keys = np.arange(5)
vectors = np.array(
    [
        [1, 1, 1],
        [-1, -1, -1],
        [1, 2, 3],
        [-1, -2, -3],
        [1, -2, -3],
    ], 
    dtype=np.float32
)
search_vector = np.array([1, 1, 1], dtype=np.float32)

index.add(keys, vectors)
matches: Matches = index.search(search_vector, 4)

for match in matches:
    assert(match.distance > -1e-6), f"Negative distance {match.distance}"

Expected behavior

Distance is always >= -epsilon, where epsilon is very small.

USearch version

v2.3.1

Operating System

Ubuntu 22.04

Hardware architecture

x86

Which interface are you using?

Python bindings

Contact Details

No response

Is there an existing issue for this?

  • I have searched the existing issues

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. added
    bug
    invalid
    on Sep 7, 2023
  2. ashvardanian commented on Sep 7, 2023

    @ashvardanian
    Member

    It might be a bit counter-intuitive, but your vectors aren’t normalized in any way, so you shouldn’t expect the inner products to be in the 0-1 range.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

buginvalid

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions