请求协助解决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 callsvinside its own definition, creating an infinite recursion loop. It’s clear you probably meant to integrateu(your original function) instead ofvitself. integrateReturns a List: Theintegrate()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 rawintegrate()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 ofvitself, which aligns with your likely intent. - Extract Integral Value: Using
$valuepulls the actual numeric result from theintegrate()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 thatcurve()sends it, fixing the "'expr' did not evaluate to an object of length 'n'" error.
内容的提问来源于stack exchange,提问作者Hung
相关产品推荐
相关产品推荐

