[(int)Math.floor(x)] or just [x]?

From: Murat Tasan (tasan_at_eecs.cwru.edu)
Date: 10/30/03


Date: Thu, 30 Oct 2003 17:14:32 -0500

here is the situation...

i have an array... and i select something from random from it.
i pick a random number x by using Math.random() and multiplying it by the
length of the array.
but this gives me a double, not an int.
so when i go to use the array, it needs an int.
in the language spec, it tells me that round-towards-zero is used when
going from floating point to integer, and the casting is done
automatically if possible.

so, given that x is a double, both of these methods are basically
equivalent:

obj = myArray[(int)Math.floor(x)]

and

obj = myArray[x]

only the top version is "safer" in some sense... it helps explain to
anyone who would ever look at the code (including the author when having
to back to it) what is going on.

now, intution says the bottom one is NO SLOWER than the top, because the
top may incur extra overhead due to the function call stack (for
Math.floor)... but i'm not sure. when the runtime environment does the
automatic rounding toward zero, does it basically go through the same
operations as Math.floor anyhow?

which one would most people here use... and most importantly why?

(note, i may come up with a small test program and try to benchmark the
two to get a quantitative answer, and i will post when i do.)

thanks again for all the help,

murat

-- 
Murat Tasan
mxt6@po.cwru.edu
tasan@eecs.cwru.edu
murat.tasan@cwru.edu
http://genomics.cwru.edu


Relevant Pages

  • Re: Is it possible to have parameters in a property?
    ... public class MyClass ... the only indexer you can declare is for the class itself. ... That's assuming it makes sense to provide access to the array in this way at all, which is not always true ). ... MyClass obj = new MyClass; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: [(int)Math.floor(x)] or just [x]?
    ... > length of the array. ... > so when i go to use the array, it needs an int. ... > automatic rounding toward zero, does it basically go through the same ... > Murat Tasan ...
    (comp.lang.java)
  • Re: [(int)Math.floor(x)] or just [x]?
    ... Murat Tasan wrote: ... > length of the array. ... > so when i go to use the array, it needs an int. ... > automatic rounding toward zero, does it basically go through the same ...
    (comp.lang.java)
  • Re: how to write array elements to console
    ... private void f{ ... Downcasting works if the Object happens to be an array at runtime for the downcast. ... public void foo(Object obj) ...
    (comp.lang.java.programmer)
  • Re: JSON array, cant access result ?!?!
    ... correct technique for looping through an array anyway. ... the first seems to be from "for (var i in obj)", ... global scope completion routine was written because ...
    (comp.lang.javascript)