Heron's Formula is a handy formula to start one's experience in learning how to program on an Nspire CAS calculator. Mathematically, Heron's formula is used to find the area of an arbitrary triangle when only the lengths of the sides are known. Let's label the sides a, b, c. The formula is in two parts. The first part calculates the "semi-perimeter" by adding the three lengths and dividing the total by 2. s = (a+b+c)/2. The second part calculates the area using the semi-perimeter.
Area = √(s*(s-a)*(s-b)*(s-c))
Here's one way Heron's can be programmed:
Define LibPub herons(a,b,c)=
Func
Local s,d,x
((a+b+c)/(2))→s
s*(s-a)*(s-b)*(s-c)→d
If d>0 Then
√(d) → x
Disp "Area is "
Return x
Else
Return "Not a Triangle."
EndIf
EndFunc
Explanation
Local s,d,x //One of the first things I learned is that functions are not allowed to change global variables; they can change only local variables, so these must be declared as local.
((a+b+c)/(2))→s //this line calculates the semi-perimeter and stores the result in s
s*(s-a)*(s-b)*(s-c)→d //this line calculate the radicand and stores it in d. This is done first because not all side lengths will make a triangle, so if d is negative, then we do not want to take the square root of it. The following chunk of code tests the radicand, and if it is not negative then we get the square root and return it in x. Otherwise, the radicand is negative, and we tell the user that there is no triangle.
If d>0 Then
√(d) → x
Disp "Area is "
Return x
Else
Return "Not a Triangle."
Disclaimer: The above code may not be the best way to program the formula, nor the most efficient, nor the most elegant; but the code works.
Have fun!
Area = √(s*(s-a)*(s-b)*(s-c))
Here's one way Heron's can be programmed:
Define LibPub herons(a,b,c)=
Func
Local s,d,x
((a+b+c)/(2))→s
s*(s-a)*(s-b)*(s-c)→d
If d>0 Then
√(d) → x
Disp "Area is "
Return x
Else
Return "Not a Triangle."
EndIf
EndFunc
Explanation
Local s,d,x //One of the first things I learned is that functions are not allowed to change global variables; they can change only local variables, so these must be declared as local.
((a+b+c)/(2))→s //this line calculates the semi-perimeter and stores the result in s
s*(s-a)*(s-b)*(s-c)→d //this line calculate the radicand and stores it in d. This is done first because not all side lengths will make a triangle, so if d is negative, then we do not want to take the square root of it. The following chunk of code tests the radicand, and if it is not negative then we get the square root and return it in x. Otherwise, the radicand is negative, and we tell the user that there is no triangle.
If d>0 Then
√(d) → x
Disp "Area is "
Return x
Else
Return "Not a Triangle."
Disclaimer: The above code may not be the best way to program the formula, nor the most efficient, nor the most elegant; but the code works.
Have fun!