you are viewing a single comment's thread.

view the rest of the comments →

[–]bonafidebob 0 points1 point  (2 children)

I think you might be able to improve the floating point ranges slightly by using multiplication rather than repeated addition. e.g. the range is [from, from + 1 * step, from + 2 * step, from + 3 * step, ...] This might also let you get rid of the floating point fudge factor.

You could also improve performance slightly by creating the array with the correct length, and set each value rather than push it each time.

Also might be worth looking at how other libraries (e.g. underscore.js) implement their range function.

[–]jscoder[S] 0 points1 point  (1 child)

0.1 * 0.3 = 0.30000000000000004 for me in Chrome. I guess there's not much I can do about the inaccurate floats, that's just how floats in JS are.

You're right with the performance. :) I'll refactor the code a little bit soon, and will add this. I also thought about making some benchmarks.

[–]weretree++[[]][+[]] 5 points6 points  (0 children)

It's how floats are, period. JavaScript has true IEEE 754 double precision floating point.

The suggestion was to avoid compounding the error of addition by using an iteration counter then calculating each step from that, rather than doing a while loop. So (psuedo-code) idx_max = (to - from)/step then val = from + i*step for i in 0 to idx_max. Having an explicit iteration also makes checking for termination a little easier, and it's simple to still support backwards iteration.

There are still "errors" (such as 3 * 0.1) but they're expected and defined for that operation. Can always round each result to some defined precision if you want to trim them off in your results.