Last active
August 27, 2021 10:43
-
-
Save Zelakolase/48466875906668f0dbd68a343d5f3fc4 to your computer and use it in GitHub Desktop.
sine function btw
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
public class sine { | |
/* | |
* This Class does sine function without any need to use Math.sin | |
* @author Morad A. | |
*/ | |
static double PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679d; | |
public static void main(String[] args) { | |
System.out.printf("%.19f\n",sin(30d)); // print the result to 19 decimal places of sin(30 deg.) | |
} | |
/* | |
* Does sine function | |
* @param in the input in deg. | |
* @return result of sine of input deg | |
*/ | |
public static double sin(double in) { | |
double ret = 0d; | |
in = toRadian(in); | |
double initOddNum = 3d; // inital odd number | |
boolean arthSwitch = false; // false: - , true : + | |
ret = in; | |
for(int i = 0;i<20;i++) { | |
if(arthSwitch) { // true / + | |
ret = ret + (power(in, initOddNum)/factorial(initOddNum)); | |
}else { // false / - | |
ret = ret - (power(in,initOddNum)/factorial(initOddNum)); | |
} | |
initOddNum = initOddNum + 2d; // to the next odd number | |
arthSwitch = !arthSwitch; // flip the switch | |
} | |
return ret; | |
} | |
/* | |
* Converts deg. to rad. | |
* @param deg the input degree | |
* @return the radian value equilivant to degree | |
*/ | |
public static double toRadian(double deg) { | |
double ret = 0d; | |
ret = deg * (PI/180d); | |
return ret; | |
} | |
/* | |
* Does factorial operation " eg. 4! " | |
* @param a the number to be factored "we'll call it x" | |
* @return the result of x! | |
*/ | |
public static double factorial(double a) { | |
if(a == 0d) return 1d; | |
return a*factorial(a-1d); | |
} | |
/* | |
* Does the power function faster than Math.pow | |
* @param x the base | |
* @param y the exponential | |
* @return the result | |
*/ | |
public static double power(double x, double y){ | |
double temp; | |
if (y == 0) { | |
return 1; | |
} | |
temp = power(x, y / 2); | |
if (y % 2 == 0) { | |
return temp * temp; | |
} | |
else { | |
if (y > 0) { | |
return x * temp * temp; | |
}else{ | |
return (temp * temp) / x; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment