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

请求协助解决R语言中含积分的函数v绘图报错问题

Fixing the Curve Plot for Function v in R

Let's break down why you're getting that error and fix it step by step:

1. The Core Issues in Your Original Code

  • Recursive Definition: You defined v <- function(x){integrate(v,0,x)} — this calls v inside its own definition, creating an infinite recursion loop. It’s clear you probably meant to integrate u (your original function) instead of v itself.
  • integrate Returns a List: The integrate() function doesn’t spit out a raw number; it returns a list with the integral value, absolute error, and other metadata. You need to extract the actual numeric result using $value.
  • Non-Vectorized Function: curve() passes a vector of x-values to the target function, but raw integrate() only works with single numeric inputs. This mismatch causes the length error.

2. Corrected Code to Plot v

First, redefine your functions properly:

# Keep your original u function
u <- function(x) { log(x^2 + 1) }

# Create a helper function that computes the integral of u from 0 to x (for a single x)
v_single <- function(x) {
  # Extract the numeric integral result from the integrate output
  integrate(u, lower = 0, upper = x)$value
}

# Vectorize the helper function so it can handle multiple x values at once
v <- Vectorize(v_single)

Now you can plot the curve without errors:

# Plot v from x=1 to x=2 with 10 points
curve(v, from = 1, to = 2, n = 10)

3. Why This Works

  • No More Recursion: We’re integrating u (the function you initially defined) instead of v itself, which aligns with your likely intent.
  • Extract Integral Value: Using $value pulls the actual numeric result from the integrate() output, so the function returns a number instead of a list.
  • Vectorization: Vectorize() wraps our single-input function so it can process the vector of x-values that curve() sends it, fixing the "'expr' did not evaluate to an object of length 'n'" error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:08:46