Skip to content

multipleOf incorrectly raises ValidationError for some floats #320

Closed
@dalehumby

Description

@dalehumby

In _validators.py, the multipleOf function incorrectly raises a ValidationError for e.g. 606.67 as not a multiple of 0.01, due to floating point errors.

Our use case is using a schema to ensure that amounts (in Dollars) are in increments of 1 cent ($0.01)

Going through the code,

quotient = 606.67 / 0.01 = 60666.99999999999
failed = int(quotient) != quotient
failed = 60666 != 60666.99999999999
failed = True

One number is a multiple of another number when the quotient is an integer. However, in this case, the quotient is very close to an integer due to floating point representation of those numbers.

The solution I see is: instance is a multiple of db if quotient is close to an integer.

I'm happy to submit a pull request, and first would like to

  1. write a unit tests for this case. Where is the best place for this test?
  2. implement an isclose method similar to math.isclose in Python 3. A previous commit removed something similar. Is there a better way of doing this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions