Java arithmetic

I am trying to create some Java classes that should work with either float or double numbers (for modeling purposes, I have to support both). Classes need to perform some basic arithmetic, as well as use trigonometric functions (sin, cos, atan2).

I tried to make a general approach. Since Java does not allow primitive types in generics, and MyClass<T extends Number> does allow Double and Float, but makes basic arithmetic impossible, I create a wrapper class around Double and Float. But this approach is not suitable as soon as I need to instantiate the value in one of the common classes.

Is there any clean way to support both float and double, without duplicating all the code for each type?

+4
source share
2 answers

From experience, if you are doing hardcore numerical work in Java, it is better to stick with primitive types. This means that generics are not suitable for this kind of work (but, of course, are great for many other purposes).

Is there any clean way to support both float and double, without duplicating all the code for each type?

You can implement a lower accuracy method in terms of higher accuracy:

 public static double calc(double x, double y) { // do the calculation and return double } public static float calc(float x, float y) { return (float)calc((double)x, (double)y); } 
+5
source

Maybe this is what you are looking for?

 class MyClass<T extends Number> { T add(T t1, T t2) { if (t1 instanceof Double) { return (T) Double.valueOf((t1.doubleValue() + t2.doubleValue())); } else if (t1 instanceof Float) { return (T) Float.valueOf(((t1.floatValue() + t2.floatValue()))); } else if (t1 instanceof Integer) { return (T) Integer.valueOf(((t1.intValue() + t2.intValue()))); } // you can add all types or throw an exception throw new IllegalArgumentException(); } public static void main(String[] args) { MyClass<Double> mc = new MyClass<Double>(); mc.add(1.0, 1.1); } } 
+4
source

All Articles