看板 Statistics 關於我們 聯絡資訊
※ 引述《ya1357977889 (HSciverce)》之銘言: : 請問一下 R能寫反函數嗎 : 如 y = 6*x^1/3 +3*x^4/3 +6 它的反函數怎麼用R找呢 : 應該說我有y值 需要求x值 : 網路上有找到類似的 : inverse = function (f, lower = -100, upper = 100) { : function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1]} 他其實是兩層函數: 第一層: function(f, lower, upper) 是input 你的function跟你要找根的範圍(lower, upper) 第二層: function(y) uniroot((function(x) f(x) - y), ...) 是在範圍內找f(x) = y的x解 回傳的是找到的x值 也就是f^(-1)(y) : square_inverse = inverse(function (x) x^2, 0.1, 100) 所以此處square_inverse是一個function,input是 function(x) x^2 : square_inverse(4) 這就是計算x^2=4的x為多少 : [1] 1.999976 因為是根據uniroot算的,而uniroot是數值逼近的方法去求解 因此,答案不會是exact uniroot會根據tolerance判斷是否收斂 你的程式範例未指定,則依據不同機器給不同的值 要自己改的話,function建議可以改這樣: inverse = function(f, interval, ...){ function(y){ uniroot(function(x) f(x) - y, interval, ...)[1] }} ## 此處的interval就是上面的lower跟upper square_inv = inverse(function(x) x^2, interval = c(0, 100), tol = 1e-10) # interval, tol可以自己設定 square_inv(4) # 2 square_inv = inverse(function(x) x^2, interval = c(0, 100), tol=1e-3) square_inv(4) # 1.999975 ## in your case funct_your_case = inverse(function(x) 6*x^1/3 +3*x^4/3 +6, interval = c(3,100)) funct_your_case(100) # 3.06176 # tol也可以不設定,就根據機器決定 : 但是有點看不太懂 : 如inverse(function (x) x^2, ""0.1, 100""<<<這是誤差值嗎 : 我把它改0.00001, 1000000 他答案就才等於2 : 另外因為套這個 再求x時 0附近會有ERROR : 所以想問問大家R有反函數的程式嗎 或是原理之類的 : 謝謝 mO__Om 其他方法的話 可以GOOGLE symbolic compuation in R 看看可不可以直接找出function的inverse function -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.248.7.74 ※ 文章網址: https://www.ptt.cc/bbs/Statistics/M.1435568188.A.A96.html ※ 編輯: celestialgod (111.248.7.74), 06/29/2015 17:03:14
memphis: 我記得R在這方面很弱 遠不及matlab 不知道是不是錯誤印象 06/29 20:16
memphis: 如果有人有經驗的 能不能給點意見, 我還沒看過類似的討論 06/29 20:17
memphis: 我在做 curve fitting 的時候遇到這議題, 弄得亂七八糟 06/29 20:19
celestialgod: symbolic部份 r確實遠遠不及matlab 06/29 23:28
celestialgod: 看會不會用rcpp call sympy... 06/29 23:29