1

In Solidity, I want to check that the numerator and denominator passed to my function evaluate to 0% < num / denom < 100%.

I tried the most direct approach: num / denom > 0 && num / denom < 1 but e.g. 1% (1 / 100 > 0 && 1 / 100 < 1) evaluates to false, because Solidity doesn't have decimals.

My other idea is num > 0 && num < denom. Can it be formally proven that that is always the same as 0% < num / denom < 100%?

1

If you're not worried about the exactly 0% and exactly 100% cases (or alternatively, the num == 0 and num == denom cases), then yes, num > 0 && num < denom is correct (with an implied denom > 1, anyway).

The proof is fairly simple: 0 < num / denom < 1 can be rewritten as 0 * denom < num < 1 * denom, which reduces to 0 < num < denom. This can further be rewritten as 0 < num && num < denom, which is equivalent to num > 0 && num < denom

-1

Please be careful with such things: The mathematical meaning of "0 < num / denom < 1", in the sense of rational or real numbers is different from the meaning in programming languages that deal with integers like Solidity.

For example, if num is 1 and denom is 2, then num / denom will be 0 in Solidity but 0.5 in the mathematical sense and thus larger than zero.

So in short: "num > 0 && num < denom" is not the correct check in Solidity, but it all depends on what you do with this afterwards.

  • But that's exactly what is being asked. Why isn't that the correct check in Solidity? Can you formally prove it? – Richard Horrocks Jun 10 '17 at 23:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.