Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Help with array

  1. Apr 15, 2010 #1
    What I need help with is the output.

    What should be our output?
    For example, [0, 1) ?
  2. jcsd
  3. Apr 15, 2010 #2


    Staff: Mentor

    The output should be the 10 elements in the array. Each array element is the number you get from integrating sin(x) on one of the intervals.

    For example, result[0] should have a number that is close to -.5403.
    Edit: that should be .4597.
    Last edited: Apr 15, 2010
  4. Apr 15, 2010 #3
    How did you get that number? I thought plain riemann sum (in this case, the right hand rule)

    Here is the short version (with no array), tested [0,1)
    Code (Text):
    #include <iostream>
    #include <cmath>
       using namespace std;
    double integrand(double);

    int main()
        const int SIZE = 10;
        const double WIDTH = 0.0005;  // (b-a)/n
        double sum_array[SIZE];
        double a = 0.0;
        double b = 1.0;
        double sum = 0.00;
        double y1 = 0;

        for (double k = a; k < b; k += WIDTH)
            y1 = integrand(k);
            sum += y1;
        cout << (sum*WIDTH) << endl;
        return 0;  

    double integrand(double x)
        double y;
        y = sin(x);
        return y;

    edited the code again (added (sum*WIDTH). I forgot about this)

    I got 0.45968 for [0, 1) using left endpoint
    Last edited: Apr 15, 2010
  5. Apr 15, 2010 #4


    Staff: Mentor

    Forgot to add 1. Make that .4597.
  6. Apr 15, 2010 #5
    OKay, so it is 1-cos(1) for [0, 1)

    Just really need to confirm that. Otherwise, even if I have perfect codes, with no REAL solution i still cant test it.
    My other classmates are giving me weird numbers.

  7. Apr 15, 2010 #6


    Staff: Mentor

    Your first post says to use the left endpoints.
    Yeah, that's what you should get.

    Some suggestions. Your integrand function can be shortened.
    Code (Text):
    double integrand(double x)
        return sin(x);
    Also, you could write a function that does essentially what you do in main. It should take three parameters: left endpoint, right endpoint, number of subintervals, and should return the computed value for that interval. The 10-element array would still be in main -- just loop through each element in the array and call your calculating function for each of the intervals 0 - 1, 1 - 2, ... 9 -10.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook