Is it possible to use some construct to replace all floats with doubles (or the opposite) without refactoring?
For example you may be implementing some mathematical system that works perfectly interchangeably with floats or doubles. In C you may use: typedef float real and then use real in your code. Changing to double involves only replacing one line of code.
Is something like this possible in Java? Or is there some generic numeric type?
This is not possible in Java in the straightforward case which you describe. However, depending on how your code works, you could write your math classes to interfaces, and have all methods that return values be implemented with both a double and a float return type. Then, you could write two implementation classes, and switch between them depending on which one you wanted to use.
This seems like overkill. Why do you want to do this?
It's actually recommended to use BigDecimal instead of float/double. Don't think java has something similar to typedef float real
No, there is no way to achieve this in Java with primitive types. There is simply no typedef equivalent and there are also no template classes. From a functional view, you could work this with the object oriented way, the methods would take a wrapper class/interface type (something like java.lang.Number) and also return results as a wrapped type.
However, I would just scrap the entire idea and only implement the double version. Callers that want to work with float can just use the double version of any method - parameters will be automatically widened to double. The results then need to be cast back to float by the caller. The conversions to and from double will cost a little speed. Or if double was just nice to have and you can make do with float, create only a float version.
In terms of raw computation speed, there is little to no difference between float and double (on a desktop CPU). The speed advantage with float usually mostly comes from the halved memory bandwidth requirements.
If its just one or a few utility classes, you could also have two sets of them (e.g. FloatMathUtil and DoubleMathUtil). It would then be up to the user to decide which one to code against (they would be entirely unrelated classes in terms of API).
You can use object-oriented aproach.
Create your own class that implements the methods your mathematical system needs. Use this class instead of float. Inside it can use whatever you want float, double or BigDecimal. You can change later how your class works without changing the rest of your system.
Take a look at Double, it will give the general idea how to build it.
Implement methods for addition, multiplication etc.
E.g.:
public class MyDecimal
{
private float value;
public MyDecimal(int value)
{
this.value = value;
}
public MyDecimal(float value)
{
this.value = value;
}
public MyDecimal multiply(MyDecimal by)
{
return new MyDecimal(value * by.value);
}
...
}
So, if you want to use double instead of float you only need to change this class.
Related
I can't find any information on this anywhere and was wondering whether such a use of a class is considered bad practise or not.
Let me explain. I have a class ToDecimalConverter which converts an integer from any base to decimal. However, I now need to add the functionality to also convert fractions. As such, I abstracted the integer conversion into a separate class and created a new class with the purpose of converting fractions. (Code isn't finished so I just added some comments to explain)
public class ToDecimalConverter {
private IntegerToDecimalConverter integerConverter;
private DoubleToDecimalConverter doubleConverter;
public double convert(String number, int baseNumber) {
this.integerConverter = new IntegerToDecimalConverter();
this.doubleConverter = new DoubleToDecimalConverter();
number = this.removeZerosAtBeginningOfNumber(number);
// split the number into integer and fraction so they can be used below:
int decimalInt = this.integerConverter.convert(integerNumber, baseNumber);
double decimalDouble = this.doubleConverter.convert(fractioNumber, baseNumber);
// add them together and return them
}
}
Now, except for the methods that remove the zero's from the start of a number and the method that splits the number into integer and fraction (both of which can easily be abstracted into their own class), the ToDecimalConverter class does nothing but group the integer and fraction converters together.
When searching online, I don't see a lot of classes being used like this. Should this be avoided or not? and if so, what are alternatives?
This meant as a more general question, the above is just to explain what I mean.
Edit: Or should I see it as a sort of mini GoF Facade pattern?
There is nothing wrong with it by default, but I would guess that you could achieve the same result with two methods. something like:
public int convertFromInt(String number, int baseNumber) {
int theConvertedInt = 0;
//Really cool convertion
return theConvertedInt;
}
public double convertFromFraction(String number, int baseNumber) {
double theConvertedInt = 0;
//Really cool convertion
return theConvertedInt;
}
Also, keep in mind that a lot of this conversions are already done by Java native classes like BigInteger, BigDecimal, Integer, Decimal, Double, the Math package and so on.
Not going into the specifics of what your class is doing, there indeed value in grouping several or many function/classes together to from a single unified API.
This is called the Facade design pattern.
The intent is that instead of relying on your client to have to know of the various classes/objects you use internally to achieve a feature and to have to look all over the place inside your implementation code is that you put in place a single entry point for given feature/set of feature. It is much better for discoverability & documentation.
Also this way, you ensure to only provide the public API that is only one or a few classes that make the facade while the implementation remains hidden and can change at any time.
I need an Expression Evaluator that can allow me to evaluate an expression such as follows:
(ItemWeight + PackageWeight) * 2
So, given the following Input:
ItemWeight = new Weight(2.0, LBS);
PackageWeight = new Weight(0.2, LBS);
Output would be: Weight(4.4, LBS)
public class Weight {
private final float value;
private final Unit unit;
public float getValue() { return value; }
public Unit getUnit() { return unit; }
public enum Unit {
LB, KG, GRAMS;
}
}
Similarly, I'd like to add/subtract two Amount objects (where amount is made up of a value and currency symbol).
Note: It is OK in my use case to assume that two values that do not have the same unit cannot be added/subtracted, etc
I read about MVEL, but it didn't seem like MVEL would be able to handle arithmetic expressions involving POJOs. Other options that came to mind are Rhino and Commons EL.
What would be a good library that I can use (and if needed extend) for solving this problem?
Thanks!
Java isn't C++; you can't overload operators.
It might not be quite as visually appealing to do it using a fluent interface, but I would say it's easier than what you're proposing.
This is interesting, because you're going to have to think about more than just EL. The idea is far more general than your Weight class. It's more like QuantityWithUnits. Here are a few of the questions you'll have to answer:
How will you prohibit addition and subtraction operations on objects with differing units?
How will you account for creating new units when you divide and multiply?
Will you allow scalar multiplication and division?
Will you disallow addition of scalars to quantities with units? Or will you silently create new objects with like units behind the scenes?
Will you have other common physics operations like powers?
How will you work with systems of units and conversions?
You may think "I'm too clever for all that; I just want to do something 'simple and practical'", but eventually you'll have to answer all these.
Consider a java project doing lots of floating point operations where efficiency and memory consumption can be important factors - such as a game. If this project targets multiple platforms, typically Android and the desktop, or more generally 32 and 64 bit machines, you might want to be able to build a single and a double precision build of your software.
In C/C++ and other lower level languages, this is easily achieved by typedef statements. You can have:
typedef float myfloat;
and the day you want to go 64 bit just change that to:
typedef double myfloat;
provided you use myfloat throughout your code.
How would one achieve a similar effect in java?
A global search and replace of "float" by "double" (or vice-versa) has the huge drawback of breaking compatibility with exterior libraries that only offer one flavor of floating point precision, chief among them certain functions of the java.lang.Math class.
Having a high-level polymorphic approach is less than ideal when you wish to remain efficient and keep memory tight (by having lots of primitive type arrays, for instance).
Have you ever dealt with such a situation and if so, what is in your opinion the most elegant approach to this problem?
The official Android documentation says this about float vs. double performance:
In speed terms, there's no difference between float and double on the more modern hardware. Space-wise, double is 2x larger. As with desktop machines, assuming space isn't an issue, you should prefer double to float.
So you shouldn't have to worry about performance too much. Just use the type that is reasonable for solving your problem.
Apart from that, if you really want to have the ability to switch between double and float, you could wrap your floatin point value in a class an work with that. But I would expect such a solution to be slower that using any floating point primitive directly. As Java does not support overloading operators, it would also make your math code much more complicated. Think of something like
double d = (a+b)/c;
when using primitives versus
MyFloat d = a.add(b).div(c);
when working with wrapper objects. According to my experience, the polymorphic approach makes maintaining your code much harder.
I will omit the part saying that for example double should be just fine etc. Others covered that more than good. I'm just assuming you want to do it - no matter what. Even for the sake of experiment to see what's the performance/memory difference - it's interesting.
So, a preprocessor would be great here. Java doesn't provide one.
But, you can use your own. Here are some existing implementations. Using javapp for example, you will have #define.
This is not practical without great pains.
While you could define your high level API's to work with wrapper types (e.g. use Number instead of a specific type and have multiple implementations of the API that uses Float or Double under the hood), chances are that the wrappers will eat more performance than you can ever gain by selecting a less precise type.
You could define high level objects as interfaces (e.g. Polygon etc.) and hide their actual data representation in the implementation. That means you will have to maintain two implementations, one using float and one for double. It probably requires considerable code duplication.
Personally, I think you are attempting to solve a non-existant conundrum. Either you need double precision, then float isn't an option, or float is "good enough", then there is no advantage of ever using double.
Simply use the smallest type that fits the requirements. Especially for a game float/double should make little difference. Its unlikely you spend that much time in math (in java code) - most likely your graphics will determine how fast you can go.
Generally use float and only switch to double for parts where you need the precision and the question disappears.
Java does not have such a functionality, aside from brute-force find-and-replace. However, you can create a helper class. Shown below, the type you will change to change the float precision is called F:
public class VarFloat {
F boxedVal;
public VarFloat(F f){
this.boxedVal = f;
}
public F getVal() { return boxedVal; }
public double getDoubleVal() { return (double)boxedVal; }
public double getFloatVal() { return (float)boxedVal; }
}
Where at all possible, you should use getVal as opposed to any of the type-specific ones. You can also consider adding methods like add, addLocal, etc. For example, the two add methods would be:
public VarFloat add(VarFloat vf){
return new VarFloat(this.boxedVal + vf.boxedVal);
}
public VarFloat addLocal(VarFloat vf){
this.boxedVal += vf.boxedVal;
return this; // for method chaining
}
I'm doing some processing of images and in my work I use the package java.awt.geom. I am use the class Point. This class extends from Point2D and inherits get methods that return double. Point is meant to be an integer representation of a point.
To access the integer x and y values in Point you need to use publicly accessible variable x and y; My question is
1) Isn't it bad practice to allow public access to an instance variable? eg. This question
2) Is there a better design of this?
Yes it is bad practice (at least by today's standards), but there are a few reasons for this...
The super-class Point2D needs to be as generic as possible
Backwards-compatibility
Convenience
In detail...
The super-class Point2D is a generic object used to represent any kind of point that can be represented in a 2D space. In order to have maximum use as a generic class, the point needs to allow for the highest level of precision possible (ie a double). This is evident by the getX() and getY() methods that return doubles. By using doubles, it allows any sub-class to be compatible with these methods, as a double is the largest primitive java number type with precision, so any sub-class that uses any other primitive numerical variable will always be able to return it as a double without losing any precision. You can therefore think of Point as being a simplified version of Point2D, that doesn't maintain any precision - however it must still conform to the abstract method declarations of the super-class Point2D. An int can be cast into a double directly by the JVM without losing any precision - if Point2D were something other than a double, you would lose some of the precision during the cast. (For example, you couldn't cast it to a float, as larger int values wouldn't be able to be directly represented as a float without chopping off some of the higher numbers)
The Point class was introduced in Java 1.0. To maintain backwards compatibility, access to these variables needs to be maintained, even though it may not be best practice. You'll notice this in other early classes, such as the variable File.separator
Point is a class that is used in a lot of places, and itself is still a pretty generic object. It is much easier/simpler/quicker for programmers to reference an int directly then it is to cast every time you want to get the value (int)getX(). It is also quicker to process by the JVM, as it doesn't need to convert an int to a double, and then back to an int again.
If you want a better design, you would probably be best to create additional methods for accessing the int values as ints - ie create the methods getXInt() and getYInt(), and then change the variables back to being non-public (provided you don't need to retain backwards compatibility).
1) Yes it is bad practise. The Point was introduced in JDK 1.0, Java always tries to keep backward compatibility that's why this weren't changed in the past I think.
There are getters for x and y. They are returning a double because of the abstract method declaration in Point2D. This isn't nice but can safely casted to an int as the value of the Point is returned which actually is an int.
2) If you need to deal with AWT you should simply accept this.
I have kind of a general java question I'm looking for an answer to. Lets say I have an object with a property height and I have a method that uses height to make some calculation. Is it better to pass the property height to the method or is it any different to pass the full object and use a getter to retrieve the value of height. I hope this makes sense.
e.g.
public getHeightInMeters(Object object) {
return object.getHeight()*x;
}
is the same, worse, better than?
public getHeightInMeters(Height height) {
return height*x;
}
It depends.
If the operation that you are performing is semantically linked to the type of object then it makes sense to pass the object. Or if you are using more than one properties of the object.
If the operation is generic, that is, it applies to an integer rather than to a specific property of the object then just accept an integer.
The second version is better. I has a less complicated signature. Since the getHeightInMeters() method only needs the height value, you should keep it simple.
The second. Does getHeightInMeters care anything about object? If not, then it doesn't need it.
All it needs is Height, so that's what you should pass it.
The second one is the best/proper way.
It's better to pass in the property height, because you break down the dependency. That is, if you change the passed in object, delete/rename method, you will end up with huge head-aches.
Furthermore, if you just pass in the property height, you will always know what goes in and what comes out.
Passing just the height information requires less overhead than the entire object, as you have less data to serialize each time. For a small app it makes no difference, but as you scale up you will incur a larger overhead.
It is the better option if that is the only property you need from the object.
class Person {
private double height;
public void setHeight(double height){
this.height = height;
}
public double getHeight(){
return height;
}
}
The convention might be that height for this class is in meters.
But you may create some convertes for other metrics
public class Converter{
public static double convertFromMeterToInch(double meters){
return meters * 'some factor you get from net'
}
public static double convertFromInchtoMeter(double inch){
return ....
}
}
That generally depends:
IF you are using more then one property of the object the first solution is better than adding more parameters. This have also sense if the operation is related only to object otherwise use the second form if this is only some atomic operation that can be performed on other objects either.
Another thing it hat get prefix should be generally used for class members, in this case it seams like it only operate on some constant and extern value. We don not the unit of it. Better naming would be for example pixelsToMetters(int pixel), in this case we know both units.
Since the getXXXX() is usually a naming convention for an accessor method, it will be part of your class, so something like this would suffice:
public double getHeightInMeters() {
return this.height*x;
}
If you need a mere converter, name it differently and pass a double, since it is doing nothing with the Object you are passing. This way you can reuse this method for any other context too.
Keep things simple!