4

I'm wondering which algorithms are used to implement math functions from the java.lang.Math class?

For example, is sin(x)(or log(x)) implemented as sum of elements of Taylor series or any other algorithm?

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
maks
  • 5,911
  • 17
  • 79
  • 123

4 Answers4

5

They're native. That means it's probably C code which just calls the FPU to do the work.

See: http://www.docjar.com/html/api/java/lang/Math.java.html

God bless

Trinidad
  • 2,756
  • 2
  • 25
  • 43
0

You can get a java library for systems which don't have native support for these methods, however most JVM use the underlying machine code instructions to do these.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

See "Elementary Functions: Algorithms and Implementation" by Jean-Michel Muller.

Jim Ward
  • 109
  • 1
  • 3
0

The answer is that it is vendor and platform dependent. Here's what the Math class javadoc says on the subject:

"Unlike some of the numeric methods of class StrictMath, all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required."

"(By default many of the Math methods simply call the equivalent method in StrictMath for their implementation.) Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math."

The chances are that a typical JVM will implement the operations as calls to C libraries that in turn use FPU instructions where available. But you can't generalise ...

If you want to math operations where the algorithms are tightly specified, you need to use StrictMath rather than Math. The StrictMath versions of the operations are (I understand) guaranteed to give the same answers on any Java platform. The downside is that they are most likely slower.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216