1 Replies - 418 Views - Last Post: 19 January 2013 - 01:55 PM

#1 Vodkacannon  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 67
  • Joined: 07-November 11

My difference Quotient Script

Posted 19 January 2013 - 11:36 AM

This is for the people that understand calculus:

I wanted a program that could calculate the slope of any function, that the user inputed, at any certain point.

The glaring issue here is that I've used eval() and that one has to input the functions in javascript format with x as the variable. I know I'm a naive programmer but I just wanted it plain and simple. No text parsing, for now.

I would like suggestions for improvement and maybe even a short bit of code.

On second thought, can eval() actually be made safer somehow?
function calculate_slope(form){
	
	var func, x, slope, first_f_x, second_f_x
	
	x = parseFloat(form.x.value) + 0.0000000001
	
	first_f_x = eval(form.func.value)
	
	x = parseFloat(form.x.value)
	
	second_f_x = eval(form.func.value)
	
	form.slope.value = (first_f_x - second_f_x) / 0.0000000001

}



Is This A Good Question/Topic? 0
  • +

Replies To: My difference Quotient Script

#2 NathanMullenax  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 83
  • View blog
  • Posts: 176
  • Joined: 23-September 12

Re: My difference Quotient Script

Posted 19 January 2013 - 01:55 PM

Instead of expecting strings like,
"var f = function(x) { return x+4; }"

you could only ask for the righthand side of the function, and then run eval on a string your program prepares. Assuming you have an input like this:
f(x)=<input type="text" name="formula"/>

You could the do turn it into a function using:
eval( 'function(x) { return ' + form.formula + '; }' )

You could make it safer by using a regular expression to ensure that the only identifier is x and that it contains no curly braces or square brackets.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1