calculator.cpp
#include "calculator.h"
double Exponential(const double power)
{
const long NUM_TERMS = 8; // the number of terms to calculate
double result = 0; // the result of our approximation
for (long i = 0; i < NUM_TERMS; i++) // for each term
{
double numerator = Power(power, i); // calculate the power raised to i
double denominator = Factorial(i); // calculate the factorial of i
result += (numerator / denominator); // divide and add in the term
}
return result; // return the approximation
}
long Factorial(const long fact)
{
long result = 1; // we start at 1 because 0! is 1
for (long i = fact; i > 0; i--) // for each non-zero number up to fact
{
result *= i; // multiply with the current result
}
return result; // return the result
}
double Power(const double base, const long power)
{
double result = 1; // we start at 1 because x^0 is 1
for (long i = 1; i <= power; i++) // for each power
{
result *= base; // multiply the base with the current result
}
return result; // return the result
}
double Sine(const double input, const long num_terms)
{
static long opr = 1; // a variable to track our current +/- operator
double result = 0; // we start our approximation at 0
for (long i = 1; i <= num_terms; i+=2) // the sine series only has odd terms
{
double numerator = Power(input, i); // raise our input to the power term
double denominator = Factorial(i); // get the factorial of current term
result += (opr * numerator / denominator); // +/- the current result
// with the new term
opr *= -1; // swap the operator
}
return result; // return the approximation
}
double Root(const double num, const long root)
{
const long NUM_ITERS = 10; // the number of iteration to do for accuracy
double result = num; // start our initial guess at the input number
for (long i = 1; i <= NUM_ITERS; i++) // for each iteration
{
double term1 = (root - 1) * result; // current approximation multiplied
// by one less than desired root
double term2 = num / Power(result, root - 1); // original input, divided
// by the current approx.
// raised to the root - 1
result = (term1 + term2) / root; // approximation is the sum of terms
// divided by the desired root
}
return result; // return final approximation
}
double Cosh(const double num)
{
// hyperbolic cosine is the average of e^x and e^-x
double term1 = Exponential(num); // get e^x
double term2 = Exponential(-1 * num); // get e^-x
double result = (term1 + term2) / 2; // average two terms together
return result; // return approximation
}