2

In one of my Java projects I am using double values to perform cosine similarity calculations.

This is the formula:

cosine = (v1 × v2)/(|v1| × |v2|).

So, in my case both numerator and denominator (after vector simplification) are doubles. After analysing my code looking for optimizations or where time is consuming, I got that the division operation (for double values) is taking more time for execution.

I tried finding different ways of dividing two numbers (using bitwise [As bitwise operators are faster])

I came across this link Division without using / operator but it is for integer or long only.

So, my questions are

  1. How can I improve the performance of division operation (for doubles) using alternative methods?

  2. If the compiler converts the double values into binary numbers while performing arithmetic operations, how does division takes place for doubles or floats? I need a bit of explanation at machine level

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • those [*divide without division operator*](https://stackoverflow.com/q/5386377/995714) questions are mainly for educating purpose, or for architectures where hardware divide instruction is not available. It's definitely a lot slower than hardware support. Emulating floating-point division in software would be even worse, unless you can don't need the full precision, in which case you can change a/b to a*(1.0/b). See [Fast 1/X division (reciprocal)](https://stackoverflow.com/q/9939322/995714) – phuclv Aug 15 '18 at 15:34

1 Answers1

0

Well, double and float value division is performed by the floating point co-processor (or the GPU in some instances).

Floating point division is an expensive operation, i do not believe there is a way to "accelerate" floating point division in Java. I believe that in order to improve the performance of your program you should try applying programming optimization techniques like using common sub-expressions:

double x = d * (lim / max) * sx;
double y = d * (lim / max) * sy; 

to...

double depth = d * (lim / max);
double x = depth * sx;
double y = depth * sy;

And Mathematics optimizations (like finding faster formulas for equivalent calculations)

Perhaps there are some "faster" sine and cosine implementations in java (developed by end users as libraries), you could check those out (or use Mat.sin and Math.cos standard methods).

Check this stack overflow answer on fast sine and cosine: Fast sine and cosine function in java

Check this article: https://www.javaworld.com/article/2077647/build-ci-sdlc/make-java-fast--optimize-.html

Hope this helps

Martín Zaragoza
  • 1,717
  • 8
  • 19