swaggest / php-json-schema

High definition PHP structures with JSON-schema based validation
MIT License
438 stars 50 forks source link

multipleOf not always behaving correctly #127

Closed ghost closed 3 years ago

ghost commented 3 years ago

Current implementation of multipleOf might lead to unexpected results. Say we have a schema of number with multipleOf = 0.01. When now the number 4.22 is input then there is an error that 4.22 is no multiple of 0.01. This happens because in https://github.com/swaggest/php-json-schema/blob/master/src/Schema.php#L348 the division yields 422.0 and casting this to integer results in 421 which does not match.

Why PHP does this I'm not sure. Likely the internal representation differs and this leads to some rounding or the like. See https://stackoverflow.com/q/3385685/6221202 for a similar problem and possible solutions.

vearutop commented 3 years ago

This problem is caused by the nature of float numbers, that infinite variety of floats is represented by finite number of bit combinations.

https://github.com/json-schema-org/json-schema-spec/issues/312 Here are a few alternative strategies to check. https://3v4l.org/6fSe8

Not sure so far how to proceed with this problem.

ghost commented 3 years ago

Wow, even the behavior in 7.0, 7.3 and 8 is different. For me it failed with 7.0 (which is EOL I know). I'm also not sure but the string casting method could work. Maybe as most accurate method we could compute the precision of the multipleOf parameter and use that as input to bcdiv?