0

I'm coding a short demo in Canvas using JS, and it's not running as smoothly as it should,mostly because there are quite a bunch of sines and cosines involved.

I need to make those calculations to draw things to the screen. The thing is, I don't need 7 decimals to know a pixel position (Two would already be overkill), so i was thinking maybe it would run a bit faster if I could limit float operations to two decimal places. ¿Is that even possible?

  • I refer you to [this](http://stackoverflow.com/a/3842276/1702990) as to why it's probably not possible. TLDR; It's probably implemented in hardware. You could try writing your own approximation however. – Sinkingpoint Mar 11 '15 at 10:33
  • Computation speed is not related to the number of decimals. If you're calling trig functions a lot in a tight loops, consider a pre-filled lookup table (populated once on page load). – Frédéric Hamidi Mar 11 '15 at 10:33
  • 1
    Also, this is the sort of micro-optimising which reeks of not having used some form of profiler – Sinkingpoint Mar 11 '15 at 10:34

2 Answers2

0

You can draw faster if you stick to integers. For example, you can draw a circle using integer-based arithmetic.

victor
  • 141
  • 2
  • Javascript doesn't have integers :( – Kos Mar 11 '15 at 10:43
  • 1
    Still, may be a good idea to stick to arithmetically "lighter" algorithms (e.g., the same example, with drawing a circle without extracting the square root). – victor Mar 11 '15 at 10:51
0

There's no way to modify the precision of a floating point type: they are fixed by hardware (and typically language standards). In a different language, you might be able to use a lower-precision type (e.g., in C you could use a float instead of a double), but that's not possible in JavaScript, as all numbers are doubles.

What you could do is use a faster approximation to the sine function. Typically, a sin/cos function consists of two steps:

  1. a "range-reduction" to find an integer n and float y on the interval [-π/4,π/4] such that x=n*π/2+y. This can't be performed using a standard mod (%) operation, as π can't be represented exactly by a floating point number.
  2. a "kernel" function to compute the appropriate sin/cos, typically using a polynomial approximation.

(you can see the V8 source here).

So there are couple of things you can do:

  • Use arguments that are already reduced to the appropriate interval, or alternatively, use an approximate reduction (i.e. y = x % Math.PI/2)

  • Use a faster (and less accurate) approximation to sin/cos: there's lots of stuff about this on the web, e.g. here.

Simon Byrne
  • 7,694
  • 1
  • 26
  • 50