Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: floating point precision #6

Open
sitch opened this issue Dec 10, 2020 · 2 comments
Open

Fix: floating point precision #6

sitch opened this issue Dec 10, 2020 · 2 comments

Comments

@sitch
Copy link
Contributor

sitch commented Dec 10, 2020

Currently this uses floats to perform arithmetic, which leads to unexpected evals over certain numerical intersections

This test currently passes, but most people's general conceptions would expect this to fail

    test "floating point arithmetic" do
      refute JsonLogic.apply(%{"+" => [0.1, 0.2]}) == 0.3
      assert JsonLogic.apply(%{"+" => [0.1, 0.2]}) == 0.30000000000000004
    end
@sitch
Copy link
Contributor Author

sitch commented Dec 10, 2020

I tried to put this in to fix it but there are some guards clauses that break, so it'll need to have individual methods looked at:

  import Kernel,
    except: [
      {:+, 2},
      {:-, 2},
      {:/, 2},
      {:*, 2},
      {:==, 2},
      {:!=, 2},
      {:>, 2},
      {:<, 2},
      {:>=, 2},
      {:<=, 2}
    ]

  def x + y do
    x |> Decimal.add(y) |> Decimal.to_float()
  end

  def x - y do
    x |> Decimal.sub(y) |> Decimal.to_float()
  end

  def x * y do
    x |> Decimal.mult(y) |> Decimal.to_float()
  end

  def x / y do
    x |> Decimal.div(y) |> Decimal.to_float()
  end

  def x == y do
    Decimal.equals?(x, y)
  end

  def x != y do
    not Decimal.equals?(x, y)
  end

  def x >= y do
    Decimal.gt?(x, y) or Decimal.equals?(x, y)
  end

  def x <= y do
    Decimal.lt?(x, y) or Decimal.equals?(x, y)
  end

  def x > y do
    Decimal.gt?(x, y)
  end

  def x < y do
    Decimal.lt?(x, y)
  end

@axelson
Copy link

axelson commented Dec 13, 2021

Although on the other hand it does match the javascript version:

Screen Shot 2021-12-13 at 11 25 13 AM

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

No branches or pull requests

2 participants