View Full Version : Simple Math
Hi,
I am trying to create a javascript that says:
add a and b together and then divide it by 2.
(a + b) / 2
How would you do this?
Choopernickel 04012003, 09:54 PM function add(num1, num2) {
sum = num1 + num2;
return sum
}
function halve(num) {
half = num/2;
return half;
}
function sumAndHalve(numA, numB) {
numC = add(numA, numB);
numD = halve(numC);
return numD
}
then, anywhere, you'd call
sumAndHalve(3,1)
I know there are easier, more terse ways to code this, but I like to keep each operation separate. Is that so wrong?
Choopernickel 04012003, 09:56 PM I posted a new thread instead of posting a reply. D'oh! Check it.
<edit by="brothercake">
I merged your answer (above) into this thread
</edit>
beetle 04012003, 10:12 PM Or make some methods! I love methods!
Number.prototype.add = function()
{
var arg, i = 0, sum = this;
while( arg = arguments[i++] )
{
sum += parseInt( arg, 10 );
}
return sum;
}
Number.prototype.divide = function( denom )
{
return this / denom;
}
var a = 4;
var b = 2;
alert( a.add( b ).divide( 2 ) );
Choopernickel 04012003, 10:16 PM thanks, brothercake.
beetle, great solution. For some reason, I don't seem to consider extending the prototype until long after the original need is fulfilled by functions. Dur!
ok thanks. would i be able to use variables already defined as the addends?
liorean 04012003, 10:23 PM Wouldn't this be cooler to have on an Array?
Array.prototype.sum=function(){
var
l=this.length,
r=0;
while(l)
r+=this.[l];
return r;
}
Array.prototype.avg=function(){
var
k,
l=k=this.length,
r=0;
while(l)
r+=this.[l];
return (r/k);
}
Then you can use [a,b].avg() for doing the job.
beetle 04012003, 10:40 PM Cooler? Yes? More practical? Your mileage may vary ;)
Choopernickel  extending the prototype is a large part of an upcoming article I'm writing for Sitepoint.com on javascript namespaces/scope :D It should be an eyeopener for many (I hope)
Choopernickel 04012003, 10:56 PM Excellent, beetle. I've gotten familiar with extending it through some string operations I've come up with, then with an Array.search() method that I think was pretty cool.
I'm SO freakin' happy to finallly have found a javascript forum where it's like, all serious javascripting and everything! :thumbsup: :o like you don't even know.
Ok here's what I'm trying to do:
Number.prototype.add = function() {
var arg, i = 0, sum = this;
while( arg = arguments[i++] ) {
sum += parseInt( arg, 10 );
} return sum;
}
Number.prototype.divide = function( denom ) {
return this / denom;
}
function calculate() {
var a = document.triangle.a.value
var b = document.triangle.b.value
var c = document.triangle.c.value
var b2 = b*b
var c2 = c*c
if (a=" ") {
document.triangle.a.value = b2.add(c2).divide( 2 )
}
else {
javascript:calculate2()
}
}
For this one I want c  b, not c + b. I've spent ages on this, and can't firure it out.
LOL Never Mind stupid question. I think I got it.
Please tell me what I am doing wrong here!
function divide(num) {
half = num/2;
return half;
}
function calculate() {
var a = document.triangle.a.value;
var b = document.triangle.b.value;
var c = document.triangle.c.value;
var b2 = b*b;
var c2 = c*c;
var a2 = a*a;
var c2b2 = c2b2;
if (a=" ") {
document.triangle.a.value = divide(c2b2);
}
else {
alert("Hello");
}
}
By the way, yes I am doing the pythagorean theorem. A few of the variables are not necessary now, but I need them later.
beetle 04022003, 12:20 AM All values retrieved from form elements are Stringtype variables. You need to convert them to Numbertype with parseInt
var f = document.triangle;
var a = parseInt( f.a.value, 10 );
var b = parseInt( f.b.value, 10 );
var c = parseInt( f.c.value, 10 );
Which is why I suspect you also had problem using methods prototyped onto the Number object ;)
Ok I see what your doing, but what is the need for the 10?
Also, I'm still getting an answer of 4.5, when I want three, with this code:
function divide(num) {
half = num/2;
return half;
}
function calculate() {
var triangle = document.triangle;
var a = parseInt( triangle.a.value, 10 );
var b = parseInt( triangle.b.value, 10);
var c = parseInt( triangle.c.value, 10);
var a2 = a*a;
var b2 = b*b;
var c2 = c*c;
var c2b2 = c2b2;
if (a=" ") {
document.triangle.a.value = divide(c2b2);
}
else {
alert("Hello");
}
}
cheesebagpipe 04022003, 01:10 AM hey beetle...
This works nicely with host arrays:
while (el = document.images[i++] )
...as they're nodelists, and must contain objects. A for loop is a better idea with user arrays (or passed arguments)  since any element that evaluates to false will break the loop.
<html>
<head>
<title>untitled</title>
</head>
<body>
<script type="text/javascript" language="javascript">
Number.prototype.add = function()
{
var arg, i = 0, sum = this;
while( arg = arguments[i++] )
{
sum += parseInt( arg, 10 );
}
return sum;
}
Number.prototype['addorama'] = function()
{
for ( sum = this, i = 0; i < arguments.length; ++i ) sum += parseInt( arguments[i], 10 );
return sum;
}
x = 100;
y = x.add(0,999);
alert(y);
x = 100;
y = x['addorama'](0,999);
alert(y);
</script>
</body>
</html>
The addorama method is copyrighted. :p
beetle 04022003, 01:46 AM True, cheesebagpipe, but why would you want to add zero? :p
Saj,
There is no division in the pythagorean theorem, so I don't know why you are dividing.
a2 + b2 = c2
where c is the hypoteneuse. (those 2s are supposed to be superscript)
So, if you are trying to solve for a given [/B]b[/B] and [/B]c[/B], your math should be
a = Math.sqrt( c*c  b*b );
Or, you can use Math.pow() if you like
a = Math.sqrt( Math.pow( c, 2 )  Math.pow( b, 2 ) );
Or, make your own Number methods
Number.prototype.sqrt = function()
{
return Math.sqrt( this );
}
Number.prototype.square = function()
{
return this.pow( 2 );
}
Number.prototype.pow = function( power )
{
return Math.pow( this, power );
}
a = ( c.square()  b.square() ).sqrt();
You know, I am obviously going crazy. I dunno. Maybe just a long day of exams and stuff.
But thanks. I've never covered math in javascript. That helps. And yes I meant to get the square root, not divide by 2 :D Just proof of my insanity.
cheesebagpipe 04022003, 02:41 AM ...why would you want to add zero? Beats me. Why would you want to pass anything but an integer? Might as well add a bit of input filtering, never hurts. Actually, I was speaking in a general sense, having fallen afoul of this a while back.
Interesting stuff here (http://www.merlyn.demon.co.uk/jsmaths.htm)...not to me, I hate "maths"...:mad:
One More question here:
How could you say:
If the value of the text box "a" is nothing, then do this. Otherwise, do this function.
I have this so far:
function calculate() {
if (a=" ") {
document.triangle.a.value = Math.sqrt(5*5  4*4);
}
else {
another_function();
}
}
cheesebagpipe 04022003, 03:02 AM if (a == "") {
beetle 04022003, 03:11 AM Originally posted by cheesebagpipe
Interesting stuff here (http://www.merlyn.demon.co.uk/jsmaths.htm)...not to me, I hate "maths"...:mad: Ehh, some good ideas, but I don't like any of the implementation.
No, that doesn't work. When I do that, nothing happens. Its just a nonworking error.
The script works fine, but the only problem is that is I fill in the text box a, it does the it replaces it with the sum and square root of b and c, even if one isn't filled in.
cheesebagpipe 04022003, 04:12 AM Saj....it would probably be a good idea to pseudocode (http://www.minich.com/education/wyo/stylesheets/pseudocode.htm) this beforehand; it's a bit unclear from this thread exactly what you had in mind. Might want to check some of these (http://www.google.com/search?hl=en&lr=&ie=UTF8&oe=UTF8&q=javascript+pythagorean) out to see working approaches. :)
brothercake 04022003, 11:45 AM Originally posted by beetle
extending the prototype is a large part of an upcoming article I'm writing for Sitepoint.com on javascript namespaces/scope :D It should be an eyeopener for many (I hope)
Keep us informed on that :)
Ok I think I have it now.
Just 2 things. What is the kill program command in js? Like in perl it's die. And, how do you say "if something does not equal this, this, and this, then do this?"
Thanks
beetle 04022003, 07:25 PM Well, the notequal operator is != and the logical AND operator is &&. The logical OR operator is 
There is no 'kill' command, but you can break out of a function using 'return' or kill a loop with 'break'.
liorean 04022003, 07:38 PM There's no analogue to kill program. Your best bet is return from within a function or break from within a block.
function(){
if(something!=somethingelse)return;
[...]
}
AnyValidIdentifier:{
[...]
if([boolean condition]){
break AnyValidIdentifier;
}
}
As for your conditional, you use the logic operators:
// ! (unary NOT)
if(!false)
statement;
//  (binary OR)
if(truefalse)
statement;
else
statement;
// && (binary AND)
if(true&&falsetrue){
statements
}else if(1!=0){
statements
}else{
statements
}
or bitwise logic operators:
// & (binary AND)
if([number whatever] & [number bitMask])
statement;
// ^ (binary XOR)
if([number whatever] ^ [number bitMask])
statement;
//  (binary OR)
if([number whatever]  [number bitMask])
statement;
// ~ (unary NOT)
if(~[number whatever])
statement;
// Not very useful used like this  all it does is invert a number.
Umm...Alright. I think I gotcha. That works well thanks :)

