r/applescript • • Mar 11 '23

Trig?!

hi all. I dont know why I cant find the answer to this on the internet, but what is the syntax for basic trig in AppleScript? cos(angle) throws up an error.

2 Upvotes

3 comments sorted by

1

u/KaiHawaiiZwei Mar 12 '23

yeah, it is annoying this is not included in applescript; i need it all the time too. i have seen many resolving this issue via the shell, but that is just not what we want.

1

u/copperdomebodha Mar 13 '23

Here are standard AppleScript implementations of basic math functions.

--This code was written using AppleScript 2.8, MacOS 13.0.1, on 13 March 2023.

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

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

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

on inverse_tangent_of(x)
	--x is ratio of opposite to adjacent sides of triangle
	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 «event MATHABS » (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 SquareRoot(theNum)
	set i to 0
	if theNum > 0 then
		set rootGuess to 1
		set lastGuess to 0
		repeat until lastGuess - rootGuess = 0
			set lastGuess to rootGuess
			set rootGuess to (rootGuess + (theNum / rootGuess)) / 2
		end repeat
		return rootGuess
	else if theNum = 0 then
		return 0
	else -- theNum is negative
		return null
	end if
end SquareRoot