You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在RStudio中求解fun1与fun2的零点及共同零点问题

嘿,我来帮你搞定这个问题~

问题分析与解法

先从数学本质入手,再给你R语言里的具体实现方案:

数学层面的核心结论

先拆解两个函数的表达式:

  • fun1(x) = -(2 * sin(x) * cos(x)),根据三角函数二倍角公式,2sin(x)cos(x) = sin(2x),所以fun1(x)其实等价于-sin(2x)
  • fun2(x) = 2 * sin(x) * cos(x),直接就是sin(2x)

那:

  1. 要找fun1(x)=0的x值,等价于-sin(2x)=0,也就是sin(2x)=0。三角函数中sinθ=0的解是θ=kπ(k为任意整数),代入得2x=kπ,所以x = kπ/2,k∈Z(Z代表整数集合)。
  2. 要找同时满足fun1(x)=0和fun2(x)=0的x值:因为fun2(x)=0同样等价于sin(2x)=0,和fun1(x)=0的条件完全一致,所以解也是x = kπ/2,k∈Z。

R语言中的求解实现

如果需要在R中计算特定区间内的根,或者验证这个结论,可以用以下两种方式:

1. 用基础函数uniroot找区间内的根

uniroot可以定位函数在单个区间内的一个根,适合找特定范围的数值解:

# 先定义你的两个函数
fun1 <- function(x) -(2 * (sin(x) * cos(x)))
fun2 <- function(x) 2 * (cos(x) * sin(x))

# 找fun1在[0, π]区间内的根
root_fun1 <- uniroot(fun1, interval = c(0, pi))
cat("fun1在[0, π]内的根:", round(root_fun1$root, 4), "\n")

# 找fun2在[0, π]区间内的根
root_fun2 <- uniroot(fun2, interval = c(0, pi))
cat("fun2在[0, π]内的根:", round(root_fun2$root, 4), "\n")

如果要找多个区间的根,可以写个小函数遍历目标范围(比如从-2π到2π):

# 自定义函数:遍历多个区间找所有根
find_multi_roots <- function(fun, start, end, step) {
  roots <- c()
  for (i in seq(start, end - step, by = step)) {
    tryCatch({
      root <- uniroot(fun, interval = c(i, i + step))$root
      # 去重,避免边界重复的根
      if (!any(abs(roots - root) < 1e-6)) {
        roots <- c(roots, root)
      }
    }, error = function(e) {
      # 区间内没有根时跳过
    })
  }
  return(roots)
}

# 找[-2π, 2π]范围内fun1的所有根
roots_fun1 <- find_multi_roots(fun1, -2*pi, 2*pi, pi/2)
cat("fun1在[-2π, 2π]内的根:", round(roots_fun1, 4), "\n")

# 找同时满足两个函数为0的根(两个方程等价,结果和上面一致)
roots_both <- find_multi_roots(function(x) fun1(x)^2 + fun2(x)^2, -2*pi, 2*pi, pi/2)
cat("同时满足fun1=0和fun2=0的根:", round(roots_both, 4), "\n")

2. 用sympy包求精确符号解

如果想要得到数学上的精确通解,可以用符号计算包sympy:

# 先安装并加载包
install.packages("sympy")
library(sympy)

# 定义符号变量x
x <- symbols("x")

# 求解fun1(x)=0的精确解
solve(fun1(x) == 0, x)

# 求解同时满足两个函数为0的解
solve(list(fun1(x) == 0, fun2(x) == 0), x)

运行后会得到形如x = pi*n/2的通式,其中n为任意整数,和我们之前的数学结论完全匹配。

内容的提问来源于stack exchange,提问作者schwartz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:15:22