AppleScript Guidebook: Essential Sub-Routines

Math Routines

Here are some useful sub-routines addressing mathematical issues.


Is a Passed Number is Odd or Even?

This simple sub-routine will determine whether a passed whole number is even or odd. A returned value of false indicates the passed number is even, a returned value of true indicates the passed number is odd.


on is_odd(this_number)
if this_number mod 2 is not 0 then
return true
else
return false
end if
end is_odd

Here's an example script using this sub-routine:


repeat
display dialog "Enter an even number:" default answer ""
try
if the text returned of the result is not "" then ¬
set the requested_number to ¬
the text returned of the result as integer
if is_odd(the requested_number) is false then exit repeat
on error
end try
end repeat


Trigonometry

Here are four routines for Trigonometric equations: sine, cosine, tangent, and inverse tangent

sine

on sine_of(x)
repeat until x >= 0 and x < 360
if x >= 360 then
set x to x - 360
end if
if x < 0 then
set x to x + 360
end if
end repeat

--convert from degrees to radians
set x to x * (2 * pi) / 360

set answer to 0
set numerator to x
set denominator to 1
set factor to -(x ^ 2)

repeat with i from 3 to 40 by 2
set answer to answer + numerator / denominator
set numerator to numerator * factor
set denominator to denominator * i * (i - 1)
end repeat

return answer
end sine_of

 

cosine

on cosine_of(x)
repeat until x >= 0 and x < 360
if x >= 360 then
set x to x - 360
end if
if x < 0 then
set x to x + 360
end if
end repeat

--convert from degrees to radians
set x to x * (2 * pi) / 360

set answer to 0
set numerator to 1
set denominator to 1
set factor to -(x ^ 2)

repeat with i from 2 to 40 by 2
set answer to answer + numerator / denominator
set numerator to numerator * factor
set denominator to denominator * i * (i - 1)
end repeat

return answer
end cosine_of


 

tangent

--x is in degrees
on tan(x)
set answer to sine_of(x) / (cosine_of(x))
return answer
end tan

 

inverse tangent

--x is ratio of opposite to adjacent sides of triangle
on inverse_tangent_of(x)
set complimentFlag to false
if x > 1 or x < -1 then
set x to 1 / x
set complimentFlag to true
else if x = 1 then
return 45.0
end if

set answer to 0
set numerator to x
set denominator to 1
set ratio to x
set factor to -(x ^ 2)

repeat while abs(ratio) > 1.0E-4
set answer to answer + ratio
set numerator to numerator * factor
set denominator to denominator + 2
set ratio to numerator / denominator
end repeat

--convert from radians to degrees
set answer to answer * 360 / (2 * pi)

if complimentFlag is true then
set answer to 90 - answer
end if

return answer
end inverse_tangent_of

on abs(numericVariable)
if numericVariable < 0 then
return -numericVariable
else
return numericVariable
end if
end abs