[問題] Codewars 6級數學題(可用Swift)

作者: pmove (金疾檸檬)   2022-12-13 19:23:39
今天嘗試用Swift解難度6級的Floating-point Approximation (I):
https://www.codewars.com/kata/58184387d14fc32f2b0012b2
結果只有測試資料Pass, 傳送過去就Fail了。
想了一個下午,最後只好看解答,
看了解答,我還是想不出來…為什麼?有人能明講,
這題解答的原理是什麼嗎?
題目很短,我順便Po在下面:
Consider the function
f: x -> sqrt(1 + x) - 1 at x = 1e-15.
We get: f(x) = 4.44089209850062616e-16
or something around that, depending on the language.
This function involves the subtraction of a pair of similar numbers when x is
near 0 and the results are significantly erroneous in this region. Using pow
instead of sqrt doesn't give better results.
A "good" answer is 4.99999999999999875... * 1e-16.
Can you modify f(x) to give a good approximation of f(x) in the neighborhood
of 0?
Note:
Don't round or truncate your results. See the testing function in Sample
Tests:.

Links booklink

Contact Us: admin [ a t ] ucptt.com