Android 計次方

小弟想寫個計供樓APP,程式大約如下:

全部都係float
rate = rate / 100 / 12;
years = years * 12;
n = (float) 1;
for (int i = 0; i < years; i++) {
        n = (1 + rate) * n;
}
a = payement * (rate * n) / (n - 1);

但結果同用Excel計有分別,
請問那個地方有問題?

小弟想寫個計供樓APP,程式大約如下:

全部都係float
rate = rate / 100 / 12;
years = years * 12;
n = (fl ...
是但 發表於 2015-7-8 11:53



    float, double 一定唔準

要準就要用 BigDecimal

TOP

回覆 2# hihihi123hk

THX,
但我BigDecimal 只識用來計"n"
"a"就唔識點用BigDecimal 來計....
程式大約如下:

n = new BigDecimal(Math.pow(1 + (rate / 100 / 12), years));
a =  payemnt * (rate / 100 / 12) * n / (n - 1);

TOP

1. that does not look like a formula for a loan at all......check your formula.

2. Excel uses floating point calculation natively, so whether you use double or float or excel, are all not exact for money calculation.  I'm guessing your difference with excel is and error in your formula

3. using BigDecimal is correct for money, but not like what you did.  You cannot use + - * / with BigDecimal.  BigDecimal class has add() subtract() multple() divide() functions.  Read the docs.

TOP

回覆 4# virtex

供樓條公式係 :
https://en.wikipedia.org/wiki/Mortgage_loan
所以我覺得我應該無錯,如有錯請指正.

另外,我Google 過應該是 float同 double的小數位不夠準確問題,

只是我不懂用BigDecimal去解決.
因小弟只是自學,本想寫多D, 見多D, 學多D.

TOP

回覆 5# 是但


1. Read the website......P is Principle....not payment.....A is payment.

2. I'm pretty sure it's not float or double issue, unless you are calculating extremely small or extremely big numbers.  When it is about float or double accuracy, the differences are very very small, are you differences very very small?

3.  Read the docs, it's pretty simple.  ie:
in double:    double a = (double) b * (double) c
in BigDecimal, you do: BigDecimal a = (new BigDecimal(b)).multiply(new BigDecimal(c));

TOP

回覆 6# virtex

1. 個名"A", P'"可能我改得唔好.

2.對呀! $1,000,000會有0.0X左右分別.

3.多謝師兄指教,等我試試.
THX

TOP

有pow function唔用?

TOP

師兄excel條formula係點?

TOP

有pow function唔用?
燕飛 發表於 2015-7-10 21:12


謝謝師兄提點,3樓已改用.POW來.

最終就寫成咁:
years = years * 12;
rate = rate / 100 / 12;
                BigDecimal big_n = (BigDecimal.valueOf(1).add(BigDecimal.valueOf(rate)))
                                .pow(years);
                BigDecimal big_a = BigDecimal
                                .valueOf(payemnt)
                                .multiply(BigDecimal.valueOf(rate))
                                .multiply(big_n)
                                .divide((big_n).subtract(BigDecimal.valueOf(1)), 2,
                                                BigDecimal.ROUND_HALF_UP);

TOP