Matematical question
Monkey Forums/Monkey Programming/Matematical question
| ||
Hi, I need to solve a simple question. I'm creating a funcion to snap a instance like it: snape_instance(32, 32) With this code, if X was 50 it should go to 64 not to 32 because the instance is near to 64 than 32. How can I create a funcion like that? Or how can I get the decimal part of a float? Like 50 / 32 = 1.56 I want the .56 part. But please only using matematics not strings. My solution was this: Method MoveSnap(sx%, sy%) Local dx#, dy# dx = (x / sx) dx = Abs(Floor(dx) - dx) If (dx > 0.5) x = (Floor(x / sx) + 1) * sx Else x = (Floor(x / sx)) * sx End dy = (y / sy) dy = Abs(Floor(dy) - dy) If (dy > 0.5) y = (Floor(y / sy) + 1) * sy Else y = (Floor(y / sy)) * sy End End But its so slow, maybe another solutions? |
| ||
Try x = ceil(x / 32.0) * 32 |
| ||
in your example fails because he always rounds up. That's the problem. I need it to always round to the nearest multiple of 32, which can be above or below. |
| ||
I'm on my android phone atm so i can't test |
| ||
X=ceil(x/32. 0-. 5) *32 (also written on my android phone, so not tested) |
| ||
buddy I do not understand your code |
| ||
He formatted it a bit funny but it seems to work:x= Ceil(x/32.0 - 0.5) *32 |
| ||
@Warpy Humm.. Thats nice! This reallt works, but how do you discover it? @Gfk thanks to translate :D |
| ||
Subtracting point five solves your rounding up issue. It's a common idiom |
| ||
Why no love for Floor?!? |
| ||
man, I just used Ceil because that's what gfk used. Vinians: here's why my code works: Ceil rounds any number up to the nearest whole number. So anything in the range N up to N+1 is rounded to N+1. Rounding to the nearest number works like so: if the number is less than N+0.5, the number is rounded down to N, and if the decimal part is greater than or equal to N+0.5, the number is rounded up to N+1. So we want everything in the range N-0.5 up to N+0.5 to be rounded to N. If you subtract 0.5 from those numbers, you get the range N-1 up to N. Calling Ceil on those numbers will round them up to N. So Ceil(x-0.5) rounds x to the nearest whole number. But you want to round to the nearest multiple of 32. So for a number x, think about what multiple of 32 it is and round that. What I mean is, think about x = y*32. Divide by 32 to get y = x/32.0. Now round y to the nearest whole number ( y = Ceil(y-0.5) ), and multiply by 32 to get the nearest multiple of 32 to x. So the closest multiple of 32 to x is Ceil(x/32.0 - 0.5)*32. I hope this explanation helps. |