cmounce [Lexaloffle Blog Feed]https://www.lexaloffle.com/bbs/?uid=24424 Weird behavior of -32768 % y <p>In PICO-8, the % operator causes numbers to wrap like this:</p> <div> <div style="max-width:800px; overflow:auto; margin-bottom:12px"> <table style="width:100%" cellspacing=0 cellpadding=0> <tr><td background=/gfx/code_bg1.png width=16><div style="width:16px;display:block"></div></td> <td background=/gfx/code_bg0.png> <div style="font-family : courier; color: #000000; display:absolute; padding-left:10px; padding-top:4px; padding-bottom:4px; "> <pre>print(-1 % 10) -- 9 print(0 % 10) -- 0 print(1 % 10) -- 1</pre></div></td> <td background=/gfx/code_bg1.png width=16><div style="width:16px;display:block"></div></td> </tr></table></div></div> <p>As I understand it, to compute x % y, you take x and add/subtract y from it, making it bigger if it's negative and smaller if it's too big, until x &gt;= 0 and x &lt; y. <strong>As long as y is not zero, the result should always be positive.</strong></p> <p>Well, -32768 % y is negative for some values of y:</p> <div> <div style="max-width:800px; overflow:auto; margin-bottom:12px"> <table style="width:100%" cellspacing=0 cellpadding=0> <tr><td background=/gfx/code_bg1.png width=16><div style="width:16px;display:block"></div></td> <td background=/gfx/code_bg0.png> <div style="font-family : courier; color: #000000; display:absolute; padding-left:10px; padding-top:4px; padding-bottom:4px; "> <pre>print(-32768 % 20000) -- negative result: -12768</pre></div></td> <td background=/gfx/code_bg1.png width=16><div style="width:16px;display:block"></div></td> </tr></table></div></div> <p>After trying a bunch of values for y, the rules look... complicated:</p> <ul> <li>If -0x4000 &lt;= y <strong>and</strong> y &lt;= 0x4000, then x % y is positive 32768 <strong>minus</strong> abs(y) a bunch of times, until it's in the proper range.</li> <li>If y &lt; -0x4000 <strong>or</strong> 0x4000 &gt; y, then x % y is -32768 <strong>plus</strong> abs(y) multiple times, but not enough times to make the number non-negative.</li> </ul> <p>Is this a bug? This doesn't seem like intended (or useful) behavior to me.</p> https://www.lexaloffle.com/bbs/?tid=35308 https://www.lexaloffle.com/bbs/?tid=35308 Tue, 10 Sep 2019 05:38:54 UTC