Simple javascript math problem
How do I express this in javascript?
9H squared plus 3H all over 2 times L
I'm working on something like:
function calculator (height, len) {
var开发者_JAVA技巧 H = height, L = len;
total = (((9 * H)*(9 * H)) + 3*H)/2)*L;
return total;
}
calculator(15, 7);
I don't care if it's terse or not, but I'm not sure the best way to handle math in javascript.
thank you.
Squaring a number x can be represented as Math.pow(x, 2)
. Also, "all over 2 times L" would mean / (2 * L)
at the end rather than the way you have it, if you do really mean:
whatever
-----------
2L
You are also missing the var
keyword before total
, which would declare it as a local variable.
Horner's method is a nice way of expressing polynomials:
function calc (height, length) {
return ((9*height + 3)*height)/(2*length);
}
http://en.wikipedia.org/wiki/Horner_scheme
Looks almost fine to me. What's the problem you're having?
The only thing I see wrong is a missing var
before total, thus making it global. Change your code to:
function calculator (height, len) {
var H = height,
L = len, // <-- subtle change: replace ; with ,
total = (((9 * H)*(9 * H)) + 3*H)/2)*L;
return total;
}
Of course, you could also factor out the 9:
total = ((81*H*H + 3*H)/2)*L;
And if you want to get even fancier, then factor out the common 3*H
as well:
total = (3*H*(27*H + 1)/2)*L;
But I'm not sure what else you're looking for here.
In "9H squared" it's only the H that is squared, so
function calculator (height, len) {
var H = height, L = len;
var total = (9*H*H + 3*H)/(2*L);
return total;
}
+1 to Andrew Cooper
(9*H)*(9*H) = 81*H^2, which i dont believe you intend
9*H*H = 9H^2 is how you intend that term
(9*H*H + 3*H) / (2*L)
or factor
(3*H)(3*H+1)/(2*L)
Which is equal to the sum of 1 + 2 + .. + 3H all divided by L (if H is an intger)
This last part probably doesn't do anything for you, but I like the identity =P
You might go about it like so...
function calculator (height, len) {
var h = height, l = len;
var total = ( 9 * Math.pow(h, 2) + 3*h ) / (2*l);
return total;
}
Don't forget making a variable with out var
prepended will make it global :)
精彩评论