Skip to content

Rewrite the scalar arithmetic functions in C - #147

Merged
EmilHvitfeldt merged 1 commit into
mainfrom
scalar-arithmetic-c
Oct 30, 2026
Merged

EmilHvitfeldt merged 1 commit into
mainfrom
scalar-arithmetic-c

Conversation

@EmilHvitfeldt

Copy link
Copy Markdown
Member

The four scalar arithmetic functions (sparse_addition_scalar(), sparse_subtraction_scalar(), sparse_multiplication_scalar() and sparse_division_scalar()) now do their work in C instead of building a new sparse vector from R vectors. The R wrappers keep the cheap shortcuts (NA, identity values, the dense val = 0 division result from #146) and then call one shared C routine with an operation tag.

On this machine a call on a small sparse vector goes from about 10 us to about 1.5 us. With one million stored doubles, addition goes from 9.8 ms to 2.6 ms, multiplication from 6.2 ms to 3.4 ms and division from 6.2 ms to 3.0 ms. Integer vectors improve less, 6.2 ms to 4.6 ms for addition.

I compared the old and new code over a grid of 1368 inputs and values, and every case where the old code succeeded gives the same result. The intended differences, all noted in NEWS.md:

  • Stored integer values that overflow now give NA with the usual "NAs produced by integer overflow" warning, as dense integer vectors do, instead of an error. An overflowing default value still errors.
  • sparse_division_scalar() now errors for sparse logical input, instead of silently accepting it.
  • Results that sparse double vectors can't store (stored Inf or NaN, or a NaN default) still error, with clearer messages.
  • A result that happens to equal the default value no longer errors.
  • A fractional val still works on sparse integer vectors when every result is a whole number, and errors otherwise.

Multiplying by 0 keeps stored NA values in C too, so the fix from #145 is not undone. The test added there fails against the earlier version of this C code.

Closes #88.

@EmilHvitfeldt
EmilHvitfeldt merged commit bd3bb92 into main Oct 30, 2026
12 of 13 checks passed
@EmilHvitfeldt
EmilHvitfeldt deleted the scalar-arithmetic-c branch October 30, 2026 03:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Speedup scalar arithmetic functions

1 participant