Skip to content

fix: prevent PHP scalar values from over-promoting array dtype - #33

Merged
CodeWithKyrian merged 1 commit into
mainfrom
fix/scalar-promotion-over-widening
Jun 15, 2026
Merged

CodeWithKyrian merged 1 commit into
mainfrom
fix/scalar-promotion-over-widening

Conversation

@CodeWithKyrian

Copy link
Copy Markdown
Contributor

This PR fixes scalar dtype promotion so that a plain PHP scalar does not force up-widening of the array's dtype — matching the intuitive expectation that $float32Array->add(5.0) stays Float32.

Motivation and Context

Previously, DType::promote() was used for both array×array and array×scalar operations. Since PHP's DType::fromValue(5.0) always returns Float64, a Float32 array combined with a PHP float scalar would promote to Float64, silently doubling memory usage and precision. Similarly, a UInt8 array plus an Int scalar would promote to Int64. This was inconsistent with how scalars combine with arrays in other numerical libraries where plain scalar values don't force up-widening.

What's Changed

  • Added DType::promote_scalar() — scalar promotion that keeps float array width and integral array type, except where conversion is required (int+float → float, UInt64+signed → Float64 for overflow safety)
  • Updated scalar_op_arithmetic and scalar_op_comparison macros to use promote_scalar
  • Filled in missing scalar dtype conversions in get_scalar_as_u8/u16/u32/u64
  • Added 6 regression tests in TypePromotionTest covering Float32+5.0, UInt8+5, Int32+10, UInt64+-1

Breaking Changes

Any code relying on scalar operations producing Float64 from Float32 arrays will now get Float32. This is a narrowing change that could affect downstream precision-sensitive code.

@CodeWithKyrian
CodeWithKyrian force-pushed the fix/scalar-promotion-over-widening branch from 12ef70e to 3ea1438 Compare June 15, 2026 12:01
@CodeWithKyrian
CodeWithKyrian merged commit 770f6b6 into main Jun 15, 2026
14 checks passed
@CodeWithKyrian
CodeWithKyrian deleted the fix/scalar-promotion-over-widening branch June 15, 2026 12:12
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.

1 participant