r - 在 R 中找到零交叉
问题描述
如果我有以下数据:
df <- structure(list(x = c(1.63145539094563, 1.67548187017034, 1.71950834939504,
1.76353482861975, 1.80756130784445, 1.85158778706915, 1.89561426629386,
1.93964074551856, 1.98366722474327, 2.02769370396797, 2.07172018319267,
2.11574666241738, 2.15977314164208, 2.20379962086679, 2.24782610009149,
2.2918525793162, 2.3358790585409, 2.3799055377656, 2.42393201699031,
2.46795849621501, 2.51198497543972, 2.55601145466442, 2.60003793388912,
2.64406441311383, 2.68809089233853, 2.73211737156324, 2.77614385078794,
2.82017033001265, 2.86419680923735, 2.90822328846205, 2.95224976768676,
2.99627624691146, 3.04030272613617, 3.08432920536087, 3.12835568458557,
3.17238216381028, 3.21640864303498, 3.26043512225969, 3.30446160148439,
3.3484880807091, 3.3925145599338, 3.4365410391585, 3.48056751838321,
3.52459399760791, 3.56862047683262, 3.61264695605732, 3.65667343528202,
3.70069991450673, 3.74472639373143, 3.78875287295614), y = c(24.144973858154,
18.6408277478876, 21.9174270206615, 22.8017876727379, 20.9766270378248,
18.604384256745, 18.4805250429826, 15.8436744335752, 13.6357170277296,
11.6228806771368, 9.4065868126964, 6.81644596802601, 4.41187500831424,
4.31911614349431, 0.678259284890563, -1.18632719250877, -2.32986407762089,
-3.84480566043122, -5.24738510499144, -5.20160089844013, -5.42094587600499,
-5.39886757202858, -5.26753920575326, -4.68727963638973, -2.73267203102102,
0.296905237887623, 2.45725152489283, 5.12102449689086, 7.13986218237411,
10.2044876281093, 14.4358946463429, 19.0643081865458, 22.8920445618834,
26.7229418763085, 31.3776791707576, 36.19058349817, 41.2843224331918,
46.3396522631345, 51.4321502764393, 56.4080998038294, 61.5215778808583,
66.6845421308734, 71.3912749310486, 76.0856977880158, 80.7039319129457,
84.4095953723555, 88.0163019647757, 89.918078622734, 91.6341473685881,
94.0404562451352)), class = c("tbl_df", "tbl", "data.frame"), .Names = c("x",
"y"), row.names = c(NA, -50L))
阴谋:
我如何找到确切的x
值y == 0
?我尝试进行插值,但它不一定给我一个y
等于零的值。有谁知道找到零交叉的功能?
解决方案
首先,可以定义一个对应的(线性)插值函数
approxfun(df$x, df$y)
结果看起来像
curve(approxfun(df$x, df$y)(x), min(df$x), max(df$x))
那些零交叉可以看作是这个函数的根。在基础 R 中有一个 function uniroot
,但它寻找一个根,而在你的情况下我们有两个。因此,一种选择是rootSolve
包装,如
library(rootSolve)
uniroot.all(approxfun(df$x, df$y), interval = range(df$x))
# [1] 2.263841 2.727803
推荐阅读
- c++ - 如何获取向量内的对象年龄?
- javascript - 在 iFrame 中加载 JavaScript 源代码
- r - 在R中将列表转换为数据框不会丢失根节点
- android - 是否可以在非 VR 模式下启动启用了 VR 的 Unity3d Android 应用程序?
- css - 我的下拉内容与我的按钮重叠,我希望它位于导航栏下方
- docker - 无法在 docker compose 中配置具有 php 支持的 nginx 反向代理
- python-3.x - 有没有办法说如果 x 是真的从同一行打印 y
- amazon-web-services - AWS Step Functions - 将输入传递给另一个任务
- sql-server - 根据特定的开始/结束值过滤数据并计算时间
- phpmailer - PhpMailer 将注册表单发送到邮箱 3 次