Skip to content

Instantly share code, notes, and snippets.

@Alvin-LB
Created January 7, 2018 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alvin-LB/4976c5035686d055227f03e51d6ab517 to your computer and use it in GitHub Desktop.
Save Alvin-LB/4976c5035686d055227f03e51d6ab517 to your computer and use it in GitHub Desktop.
package com.bringholm.javatest;
public class Main {
private static double EULER_MASCHERONI_CONSTANT = 0.577215664901532860606512090082;
public static void main(String[] args) {
System.out.println(cosineIntegral(1));
}
static double cosineIntegral(double arg) {
double result = naturalLog(arg);
for (int n = 1; n <= 15; n++) {
double term = intPower(arg, 2 * n) / (factorial(2 * n) * 2 * n);
if (n % 2 == 0) {
result += term;
} else {
result -= term;
}
}
return result + EULER_MASCHERONI_CONSTANT;
}
static double naturalLog(double arg) {
if (arg > 1) {
double inverse = 1.0 / arg;
return -computeNaturalLogMaclaurin(inverse);
} else {
return computeNaturalLogMaclaurin(arg);
}
}
static double computeNaturalLogMaclaurin(double arg) {
double result = 0;
for (int n = 1; n <= 50; n++) {
double term = 1.0 / n * intPower(arg - 1, n);
if (n % 2 == 0) {
result -= term;
} else {
result += term;
}
}
return result;
}
/*
* If this were to be done properly, one should build in a way to use Stirling's approximation for large values.
* This implementations only handles values up to 15.
*/
static int factorial(int arg) {
int result = 1;
for (int i = arg; i > 1; i--) {
result *= i;
}
return result;
}
static double intPower(double arg, int power) {
double result = arg;
for (int i = 1; i < power; i++) {
result *= arg;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment