作者pmove (熱臉迎人滿是傷)
看板MacDev
標題[問題] Codewars 6級數學題(可用Swift)
時間Tue Dec 13 19:23:39 2022
今天嘗試用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:.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.161.9.149 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/MacDev/M.1670930622.A.315.html
→ pmove: 我想出來了,只用到簡單公式,(x+1) * (x- 1.161.9.149 12/13 20:49
→ pmove: 1) = x^2 - 1 ,討論區還有人說要用到泰勒 1.161.9.149 12/13 20:49
→ pmove: 展開式…笑死 1.161.9.149 12/13 20:49
→ pmove: 這題拿去問New Bing, 它可以解的出來喔,只 1.161.38.179 03/26 10:12
→ pmove: 是程式碼累贅了一點 1.161.38.179 03/26 10:12