# Integrate a function from -1 to 1 [closed]

Create a function or program that takes any continuous, well-defined, single-input function (f(x)=...) and returns an approximate integration from -1 to 1. (at least 3 significant digits or more of precision)

Functions will be treated as programs, with arguments as inputs and returns as outputs.

As always, smallest byte length wins.

EXAMPLES:
y=x^2: ~0.6667
y=e^x: ~2.3504
y=πx^2+ex+1: ~4.0944

For languages where a function isn't a passable value (e.x. c, c++, etc.) the input function DOES NOT count towards character count.

• “Well-defined” is not (well) defined :-). What exactly do you mean by that? Commented May 16 at 15:52
• @LuisMendo well-defined function just means the function shouldnt depend on the domain and doesn't affect the code really Commented May 16 at 16:06
• I believe some answers unavoidably fail case f(x)=max(0,1e10*(x-1+1e-10)). Can bound derivative to avoid
– l4m2
Commented May 16 at 16:48
• Yeah I’m not seeing how this can be done with full generality. I feel like for any solution an adversarial input could be constructed Commented May 16 at 18:37

## JavaScript (ES6), 63 bytes

Expects a single-argument function f(x){...}

I=f=>(Array(2e+3).fill.map(n=>s+=f(i+=1e-3),s=0,i=-1)|s)*1e-3


#### Explanation:

I=f=>                  // define a function, I
(
Array(2e+3).fill // create an array with 2000 elements
.map(              // use the array as a REPEAT n TIMES loop
n=>s+=f(i+=1e-3),// add sample to sum, increment i by dx
s=0,             // initialize sum
i=-1             // start at -1
)|s                // return sum, not the array

)*1e-3               // multiply by dx



Try it online!

• 39 bytes But does it really give 3 correct decimal places? Commented May 16 at 15:26
• I recommend holding off for a week on answering your own challenges, especially if doing so using a popular language.
Commented May 16 at 15:31
• Makes sense! Will do in the future! Commented May 16 at 15:32

# Python, 48 bytes

f=lambda y,p=1e5:p>-1e5and y(p/1e5)/1e5+f(y,p-1)


Attempt This Online!

# NARS2000, 4 bytes

¯1(your function)∫1

• Turns out a function isn't a passable value in NARS2000, but that just saves you a character according to OP. E.g. ¯1{⍵*2}∫1 counts as just ¯1∫1 — however, that's 8 bytes, as NARS2000 uses two bytes per character. If you want to pass a function in, you have to define an operator like {¯1⍺⍺∫1} and call it with a dummy argument.
x←((0,⍳1E5)÷5E4)-1⋄⍎'2E¯5×+/',⎕