-
Notifications
You must be signed in to change notification settings - Fork 11.8k
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
Add SignedMath with math utilities for signed integers #2686
Conversation
rotcivegaf
commented
May 20, 2021
- Tests
- Documentation
- Changelog entry
Hello @rotcivegaf I'm sorry we haven't reached out yet. This PR resurfaced as we are planning for the next release and we would love to merge it. Still some small issues must be addressed:
Can you have a go at this ? |
Sorry for the delay, I was very busy In the second point, when I remove the cast, I get this error from the compiler: The other option I thought of is to replace that line with: int256 r;
if(a % b != 0) r = 1; I work in the first point, in this days |
Noted. I think this point is less controversial, as it should not affect the produce bytecode
|
In the ceilDiv signed average function, I think your idea its good, I commited In the average signed average function, I try do with this way: function average(int256 a, int256 b) internal pure returns (int256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
} But when calculate with an even signed number and an odd number, the return number is one(1) integer greater than the expect, this cause because this part of the equation (a % 2 + b % 2), I think the problem is because we have the number 0 I worked in this ugly solution, but I still thinking in another better function average(int256 a, int256 b) internal pure returns (int256) {
if ((b < 0 && a > 0 && -b < a) || (a < 0 && b > 0 && -a < b))
return (a / 2) + (b / 2) + (((a % 2 + b % 2) - 1) / 2);
if ((b < 0 && a > 0 && -b > a) || (a < 0 && b > 0 && -a > b))
return (a / 2) + (b / 2) + (((a % 2 + b % 2) + 1) / 2);
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
} |
This formula on StackOverflow looks really neat:
|
should we use that for Unsigned Math ? I guess it would be more gas efficient |
Well with unsigned values its more complicated we have the number 0, and this a problem
But I use this idea in Math.sol to make another PR EDIT: I update the code, the average function its ugly but works, I will research more to improve it. Any help are welcome |
I keep trying to adapt the formula in an elegant way but I can't find one. The issue is that the formula seems to round towards negative infinity and we want it to round to zero. |
I've refactored the We still need a changelog entry and some documentation. I'll work on that tomorrow |
Co-authored-by: Francisco Giordano <[email protected]>
@Amxx I've removed Please merge if it looks good. |
I'm AFK, but I want to congratulate them |