Created
January 7, 2018 12:39
-
-
Save Alvin-LB/4976c5035686d055227f03e51d6ab517 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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