<p>I need to calculate <code>Math.exp()</code> from java very frequently, is it possible to get a native version to run faster than <strong>java</strong>'s <code>Math.exp()</code>??</p>

<p>I tried just jni + C, but it's slower than just plain <strong>java</strong>.</p>

[{'answer_id': 66416, 'author': 'jjnguy', 'author_id': 2598, 'author_profile': 'https://Stackoverflow.com/users/2598', 'pm_score': 3, 'selected': False, 'text': "<p>Use Java's.  </p>\n\n<p>Also, cache results of the exp and then you can look up the answer faster than calculating them again.</p>\n"}, {'answer_id': 66439, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 3, 'selected': False, 'text': "<p>You'd want to wrap whatever loop's calling <code>Math.exp()</code> in C as well. Otherwise, the overhead of marshalling between Java and C will overwhelm any performance advantage.</p>\n"}, {'answer_id': 66447, 'author': 'Alan Krueger', 'author_id': 7708, 'author_profile': 'https://Stackoverflow.com/users/7708', 'pm_score': 0, 'selected': False, 'text': "<p>Since the Java code will get compiled to native code with the just-in-time (JIT) compiler, there's really no reason to use JNI to call native code.</p>\n\n<p>Also, you shouldn't cache the results of a method where the input parameters are floating-point real numbers.  The gains obtained in time will be very much lost in amount of space used.</p>\n"}, {'answer_id': 66450, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 0, 'selected': False, 'text': '<p>The problem with using JNI is the overhead involved in making the call to JNI.  The Java virtual machine is pretty optimized these days, and calls to the built-in Math.exp() are automatically optimized to call straight through to the C exp() function, and they might even be optimized into straight x87 floating-point assembly instructions.</p>\n'}, {'answer_id': 66462, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 2, 'selected': False, 'text': "<p>The real question is, has this become a bottle neck for you? Have you profiled your application and found this to be a major cause of slow down?<br><br> If not, I would recommend using Java's version. Try not to pre-optimize as this will just cause development slow down. You may spend an extended amount of time on a problem that may not be a problem.<br>\n<br>\nThat being said, I think your test gave you your answer. If jni + C is slower, use java's version. </p>\n"}, {'answer_id': 66477, 'author': 'tonylo', 'author_id': 4071, 'author_profile': 'https://Stackoverflow.com/users/4071', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s simply an overhead associated with using the JNI, see also:\n<a href="http://java.sun.com/docs/books/performance/1st_edition/html/JPNativeCode.fm.html" rel="nofollow noreferrer">http://java.sun.com/docs/books/performance/1st_edition/html/JPNativeCode.fm.html</a></p>\n\n<p>So as others have suggested try to collate operations that would involve using the JNI.</p>\n'}, {'answer_id': 66515, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 2, 'selected': False, 'text': "<p>You might be able to get it to run faster if you do them in batches.  Making a JNI call adds overhead, so you don't want to do it for each exp() you need to calculate.  I'd try passing an array of 100 values and getting the results to see if it helps performance.</p>\n"}, {'answer_id': 66523, 'author': 'user9116', 'author_id': 9116, 'author_profile': 'https://Stackoverflow.com/users/9116', 'pm_score': 0, 'selected': False, 'text': "<p>Write your own, tailored to your needs.</p>\n\n<p>For instance, if all your exponents are of the power of two, you can use bit-shifting. If you work with a limited range or set of values, you can use look-up tables. If you don't need pin-point precision, you use an imprecise, but faster, algorithm.</p>\n"}, {'answer_id': 66536, 'author': 'Dan Dyer', 'author_id': 5171, 'author_profile': 'https://Stackoverflow.com/users/5171', 'pm_score': 0, 'selected': False, 'text': "<p>There is a cost associated with calling across the JNI boundary.</p>\n\n<p>If you could move the loop that calls exp() into the native code as well, so that there is just one native call, then you might get better results, but I doubt it will be significantly faster than the pure Java solution.</p>\n\n<p>I don't know the details of your application, but if you have a fairly limited set of possible arguments for the call, you could use a pre-computed look-up table to make your Java code faster.</p>\n"}, {'answer_id': 66553, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 0, 'selected': False, 'text': "<p>There are faster algorithms for exp depending on what your'e trying to accomplish.  Is the problem space restricted to a certain range, do you only need a certain resolution, precision, or accuracy, etc.</p>\n\n<p>If you define your problem very well, you may find that you can use a table with interpolation, for instance, which will blow nearly any other algorithm out of the water.</p>\n\n<p>What constraints can you apply to exp to gain that performance trade-off?</p>\n\n<p>-Adam</p>\n"}, {'answer_id': 66565, 'author': 'Daniel Spiewak', 'author_id': 9815, 'author_profile': 'https://Stackoverflow.com/users/9815', 'pm_score': 5, 'selected': True, 'text': '<p>+1 to writing your own exp() implementation.  That is, if this is <em>really</em> a bottle-neck in your application.  If you can deal with a little inaccuracy, there are a number of extremely efficient exponent estimation algorithms out there, some of them dating back centuries.  As I understand it, Java\'s exp() implementation is fairly slow, even for algorithms which must return "exact" results.</p>\n\n<p>Oh, and don\'t be afraid to write that exp() implementation in pure-Java.  JNI has a lot of overhead, and the JVM is able to optimize bytecode at runtime sometimes even beyond what C/C++ is able to achieve.</p>\n'}, {'answer_id': 67312, 'author': 'TSK', 'author_id': 9959, 'author_profile': 'https://Stackoverflow.com/users/9959', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>I run a fitting algorithm and the minimum error of the fitting result is way larger\n  than the precision of the Math.exp().</p>\n</blockquote>\n\n<p>Transcendental functions are always much more slower than addition or multiplication and a well-known bottleneck. If you know that your values are in a narrow range, you can simply build a lookup-table (Two sorted array ; one input, one output). Use Arrays.binarySearch to find the correct index and interpolate value with the elements at [index] and [index+1]. </p>\n\n<p>Another method is to split the number. Lets take e.g. 3.81 and split that in 3+0.81.\nNow you multiply e = 2.718 three times and get 20.08.</p>\n\n<p>Now to 0.81. All values between 0 and 1 converge fast with the well-known exponential series</p>\n\n<p>1+x+x^2/2+x^3/6+x^4/24.... etc.</p>\n\n<p>Take as much terms as you need for precision; unfortunately it's slower if x approaches 1. Lets say you go to x^4, then you get 2.2445 instead of the correct 2.2448</p>\n\n<p>Then multiply the result 2.781^3 = 20.08 with 2.781^0.81 = 2.2445 and you have the result\n45.07 with an error of one part of two thousand (correct: 45.15).</p>\n"}, {'answer_id': 424985, 'author': 'martinus', 'author_id': 48181, 'author_profile': 'https://Stackoverflow.com/users/48181', 'pm_score': 4, 'selected': False, 'text': '<p>This has already been requested several times (see e.g. <a href="https://stackoverflow.com/questions/412019/code-optimizations#412988">here</a>). Here is an approximation to Math.exp(), copied from <a href="http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/" rel="nofollow noreferrer">this blog posting</a>:</p>\n\n<pre><code>public static double exp(double val) {\n    final long tmp = (long) (1512775 * val + (1072693248 - 60801));\n    return Double.longBitsToDouble(tmp &lt;&lt; 32);\n}\n</code></pre>\n\n<p>It is basically the same as a lookup table with 2048 entries and linear interpolation between the entries, but all this with IEEE floating point tricks. Its 5 times faster than Math.exp() on my machine, but this can vary drastically if you compile with -server.</p>\n'}, {'answer_id': 15155829, 'author': 'reverse_engineer', 'author_id': 1241315, 'author_profile': 'https://Stackoverflow.com/users/1241315', 'pm_score': 0, 'selected': False, 'text': '<p>It might not be relevant any more, but just so you know, in the newest releases of the OpenJDK (see <a href="http://hg.openjdk.java.net/jdk7u/jdk7u/hotspot/rev/6759698e3140" rel="nofollow">here</a>), Math.exp should be made an intrinsic (if you don\'t know what that is, check <a href="http://bad-concurrency.blogspot.co.uk/2012/08/arithmetic-overflow-and-intrinsics.html" rel="nofollow">here</a>).</p>\n\n<p>This will make performance unbeatable on most architectures, because it means the Hotspot VM will replace the call to Math.exp by a processor-specific implementation of exp at runtime. You can never beat these calls, as they are optimized for the architecture...</p>\n'}, {'answer_id': 23963586, 'author': 'Renaud', 'author_id': 125617, 'author_profile': 'https://Stackoverflow.com/users/125617', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://commons.apache.org/proper/commons-math/" rel="nofollow">Commons Math3</a> ships with an optimized version: <code>FastMath.exp(double x)</code>. It did speed up my code significantly. </p>\n\n<p><a href="http://chasethedevil.blogspot.ch/2013/04/a-fast-exponential-function-in-java.html" rel="nofollow">Fabien</a> ran some tests and found out that it was almost twice as fast as <code>Math.exp()</code>:</p>\n\n<pre><code> 0.75s for Math.exp     sum=1.7182816693332244E7\n 0.40s for FastMath.exp sum=1.7182816693332244E7\n</code></pre>\n\n<p>Here is the javadoc: </p>\n\n<p>Computes exp(x), function result is nearly rounded. It will be correctly rounded to the theoretical value for 99.9% of input values, otherwise it will have a 1 UPL error.</p>\n\n<p>Method:</p>\n\n<pre><code>    Lookup intVal = exp(int(x))\n    Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );\n    Compute z as the exponential of the remaining bits by a polynomial minus one\n    exp(x) = intVal * fracVal * (1 + z)\n</code></pre>\n\n<p>Accuracy: Calculation is done with 63 bits of precision, so result should be correctly rounded for 99.9% of input values, with less than 1 ULP error otherwise.</p>\n'}]
['https://Stackoverflow.com/questions/66402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9774/']