Reputation: 1808
I have a function I am calling to find the derivative at a point, if I hard code the number into the script, I get the right answer, but if I use a variable with the same number, I get a completely wrong answer.
HTML
Point<br>
<input type="text" name="point" id="point" class="form"><br>
<p id="submit" onclick="submit()" name="solve">click</p><br>
Script
<script type="text/javascript">
function diff(f) {
return function(x) { return (f(x+.0000000001)-f(x))/.0000000001 };
}
function f(x) {
return x*x+2*x+1;
}
fprime = diff(f);
function submit() {
var point = document.getElementById("point").value;
console.log(point); //-0.5
var q = fprime(-0.5); //Will output 1
var w = fprime(point); //Will output 749999998.98
}
Any idea on why or how to fix?
Upvotes: 0
Views: 183
Reputation: 388316
The problem is point is a string, not a number, so convert the value to a number using parseFloat() or use a unary operator as below
var point = +document.getElementById("point").value;
Demo: Fiddle
Upvotes: 2