开发者

How to approximate double?

开发者 https://www.devze.com 2023-01-02 20:01 出处:网络
How to I write a function that approximates a double in the following manner, returnin开发者_如何转开发g an int:

How to I write a function that approximates a double in the following manner, returnin开发者_如何转开发g an int:

function (2.3) -> 2
function (2.7) -> 3
function (-1.2) -> -1
function (-1.7) -> -2


Is this homework? Because there's a library function to do this: Math.round()

If you're actually trying to implement something close to this yourself, one way to do so is to take the double and explicitly cast it into an int.

For the case of positive numbers, this would essentially truncate it (e.g., 5.99 becoming 5.00).

Now you can cast it back to double, and deduct it from your original number. This would leave you with a number between 0 and 0.99...

Compare it to 0.50 and decide whether to round up or round down. If you round down, take the truncated number, otherwise take the truncated + 1.


How about:

Math.round

You could get overflow problems converting a double to an int - this actually returns a long for that reason.


public int homeworkFunction(double x) {
 return (int)(Math.signum(x) * Math.min(Math.round(Math.abs(x)) , Integer.MAX_VALUE);
}


Piece of cake, man:

private double round(double d, int numbersAfterDecimalPoint) {
    long n = Math.pow(10, numbersAfterDecimalPoint);
    double d2 = d * n;
    long l = (long) d2;
    return ((double) l) / n;
}


You can use the Math.round method for that, see https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html.


I have never used Java, but I am 100 % sure there is a Round or Math.Round function to use for this!


Without Math.round(), you can use

public long homeworkFunction(double x) {  
    return (long)(x > 0 ? x + 0.5 : x - 0.5));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消