I have build a basic RPN calculator with Swift and I need to add those functions: sine, cosine, tangent, reciprocal (1/x), log (base) & log (base10). Here is the code that I have for the basic operations:
import Foundation
import UIKit
class CalculatorEngine: NSObject
{
var operandStack = Array<Double>() //array
func updateStackWithValue(value: Double)
{ self.operandStack.append(value) }
func operate(operation: String) ->Double
{ switch operation
{
case "×":
if operandStack.count >= 2 {
return self.operandStack.removeLast() * self.operandStack.removeLast()
}
case "÷":
if operandStack.count >= 2 {
return self.operandStack.removeFirst() / self.operandStack.removeLast()
}
case "+":
if operandStack.count >= 2 {
return self.operandStack.removeLast() + self.operandStack.removeLast()
}
case "−":
if operandStack.count >= 2 {
return self.operandStack.removeFirst() - self.operandStack.removeLast()
}
case "√":
if operandStack.count >= 1 {
return sqrt(self.operandStack.removeLast())
}
default:break
}
return 0.0
}
Here is an implementation of those basic functions in Swift. I'll let you put that into your RPN calculator, since that is your assignment.
The built-in trig functions need input in radians, so you have to convert by multiplying by pi
and dividing by 180.0
.
func sine(degrees: Double) -> Double {
return sin(degrees * M_PI / 180)
}
func cosine(degrees: Double) -> Double {
return cos(degrees * M_PI / 180)
}
func tangent(degrees: Double) -> Double {
return tan(degrees * M_PI / 180)
}
func log(n: Double, base: Double) -> Double {
return log(n) / log(base)
}
func reciprocal(n: Double) -> Double {
return 1.0 / n
}
For log(base 10) just use the built-in log10(n: Double) -> Double