简体   繁体   中英

converting python to java float vs double

I need to convert the following python code to Java and remember from the past that handling decimal values must be done carefully otherwise the results will not be accurate. My question is, can I use doubles for all non-interger values given doubles are more accurate that floats?

Here is my start of the conversion:

Python code

def degrees(rads):
    return (rads/pi)*180


def radians(degrees):
return (degrees/180 * pi)


def fnday(y, m, d, h):
a = 367 * y - 7 * (y + (m + 9) // 12) // 4 + 275 * m // 9
a += d - 730530 + h / 24
return a

Java conversion

public double degress(double rads)
{
    return (rads/PI)*180;
}

public double radians(double degrees)
{
    return (degrees/180 * PI);
}

public double fnday(int y, int m, int d, int h)
{
    double a = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9;
    a += d - 730530 + h / 24;
    return a;
}

I know it may be a simple answer but I need to know the postion of the moon and sun for the app and do not want to rely on an api for this data. I simple want to put in the latitude and longitdue and get the sun and moon rise and set times.

Using a double for each variable would suffice; however, you have an issue that results from integer division:

double a = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9;

If I were you, I'd change y , m , d , and h to all be double s, so you retain the decimal places when dividing:

public double fnday(double y, double m, double d, double h) {
    double a = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9;

    a += d - 730530 + h / 24;

    return a;
}

If you need a really big precision, the best way is use, java.lang.BigDecimal , that extends from java.math.Number.

You can even use your existing doubles if you need:

double d = 67.67;
BigDecimal bd = new BigDecimal(d);

But you will need to use the methods from the class like this:

public BigDecimal degress(BigDecimal rads)
{
    BigDecimal pi = new BigDecimal(PI);
    return (rads.divide(pi))*180;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM