Advertisement
TripleAlpha

bigdec cos impl

Jan 25th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. public static BigDecimal cosine(BigDecimal x) {
  2. final int SCALE = 18;
  3. final int ROUNDING_MODE = BigDecimal.ROUND_HALF_EVEN;
  4.  
  5. BigDecimal currentValue = BigDecimal.ONE;
  6. BigDecimal lastVal = currentValue.add(BigDecimal.ONE);
  7. BigDecimal xSquared = x.multiply(x);
  8. BigDecimal numerator = BigDecimal.ONE;
  9. BigDecimal denominator = BigDecimal.ONE;
  10. int i = 0;
  11.  
  12. while(lastVal.compareTo(currentValue) != 0) {
  13. lastVal = currentValue;
  14.  
  15. int z = 2 * i + 2;
  16.  
  17. denominator = denominator.multiply(BigDecimal.valueOf(z));
  18. denominator = denominator.multiply(BigDecimal.valueOf(z - 1));
  19. numerator = numerator.multiply(xSquared);
  20.  
  21. BigDecimal term = numerator.divide(denominator, SCALE + 5, ROUNDING_MODE);
  22.  
  23. if(i % 2 != 0) {
  24. currentValue = currentValue.add(term);
  25. } else {
  26. currentValue = currentValue.subtract(term);
  27. }
  28. i++;
  29. }
  30. return currentValue;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement