0

I'm trying to make a graphing calculator in javascript. Today I ran into a problem that I do not know how to fix. Here is the code.

var step = 0.5;
for (var i = -size; i <= size; i+= step){
    if(given!=null){
        func = eval(given);
        console.log("x: " + x + " y: " + func);
    } else {
        func = -(x);
    }
    points[i+size] = new THREE.Vector3(x,0,func);
    x+=step;
}

You can ignore the Vector stuff, my question is about the inaccuracy. When I make the step any lower than 0.5, javascript will make mistakes. This is what happens when I change step to 0.05.

x:-14 y: 0.27090578830786904
x: -13.95 y: 0.36565262028262135
x: -13.899999999999999 y: 0.456745972144196

There are more too it, but I stopped at -13 because that's where the problem starts. As you can see, I want it to return -13.90, but it did not work. I tried rounding it down, but it will stop working again when x is positive. Please help. Thanks in advance.

user1932868
  • 69
  • 2
  • 7

1 Answers1

0

Change this:

console.log("x: " + x + " y: " + func)

To this:

console.log("x: " + x.toFixed(2) + " y: " + func)
barak manos
  • 29,648
  • 10
  • 62
  • 114