using vector objects for calculational formulas

I am working on a homework problem that I cant figure out. I have been working on it for 4 days now.

The question is worded:
Write a program that reads the time and vertical velocity data from the file and stores the data in either an array or vector object. The program should then send that data to a function that will perform numerical differentiation on the data using the secant method to estimate the acceleration at each time step.

The part of the question you don't see is asking about altitude calculations. I can figure that out myself if I can just figure out this first part.

I have been able to get it to work up till my void calculateAccelerationArray function is actually written at the bottom. I guess I don't understand how to actually use vectors make these calculations. I am pretty sure I have written the equations correctly. And the errors I have gotten have not been due to the eqns. Can anyone please help me understand these? I have read the tutorials on this site already.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <cmath>
#include <fstream>
#include <vector>

using namespace std;

void calculateAccelerationArray(vector<double> t, vector<double>& p, vector<double> v, vector<double>& a);
void displayAcceleration(vector<double> t, vector<double> p, vector<double> v, vector<double> a);
vector<double> t;
vector<double> v;
vector<double> a;
vector<double> p;
vector<double> n;
vector<double> Acceleration, Altitude;
double Number;
int main()
{
double Time, Velocity;
const int Length_of_Line(50);
char quit, string1[Length_of_Line];
std::ifstream Rocket_Data_Input;
Rocket_Data_Input.open("rocketVelocityData.txt");         Rocket_Data_Input.getline(string1,Length_of_Line);
if (Rocket_Data_Input.fail()) // Checks for proper opening of the report.
    {
    cerr << " Your Report failed to open. \n";
    }
    cout << " Number  " << "  TIME  " << "    Velocity    " << endl;
while (!Rocket_Data_Input.eof()) // Takes data from input file.
    {
    Rocket_Data_Input >> Time >> Velocity;
    for (Number=0;Number<=t.size();Number++);
    cout << "   " << left << setw(5) << Number << "   " << left << setw(8) <<
         Time << left << setprecision(12) << setw(16) << Velocity << endl;
    t.push_back(Time);
    v.push_back(Velocity);
    calculateAccelerationArray(t, p, v, a);
    }
//    cout << t.size() << '\n';
//    cout << v.size() << '\n';

    quit = '\0';            while (quit != 'q')
    {   cout << "Press q to quit ";
        cin >> quit;
    }
    return EXIT_SUCCESS;
}

void calculateAccelerationArray(vector<double> t, vector<double>& p, 
     vector<double> v, vector<double>& a)
{
    Acceleration = a;
    Altitude = p;
    for (Number=0;Number<=t.size();Number++)
    {
//    cout << Number << endl;
    if (Number = 1)
        {
        a = (Velocity.at(Number+1)-Velocity.at(Number))/(Time.at(Number+1)-
             Time.at(Number));
        p = 0;
        cout << a << "    " << p << endl;
        }
    else if (Number > 1 && Number < 174)
        {
            a = (Velocity.at(Number+1)-Velocity.at(Number-1))/(Time.at
                 (Number+1)-Time.at(Number-1));
            p = p.at(Number-1)+((t.at(Number)-t.at(Number-1))*((v.at(Number)
                +v.at(Number-1))/2));
        }
    else ( Number == 174)
        {
            a = (v.at(Number)-v.at(Number-1))/(t.at(Number)-t.at(Number-1));
            p = p.at(Number-1)+((t.at(Number)-t.at(Number-1))*((v.at(Number)
                   +v.at(Number-1))/2));
            break;
        }
    }
}
void displayAcceleration(vector<double> t, vector<double> p, vector<double> v,
      vector<double> a);
{
}
Last edited on
closed account (o3hC5Di1)
Hi there,

Trying to compile your code throws up a lot of errors:

main.cpp:60:19: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
     if (Number = 1)


if (Number = 1) should be if (Number == 1).



main.cpp:62:14: error: ‘Velocity’ was not declared in this scope

         a = (Velocity.at(Number+1)-Velocity.at(Number))/(Time.at(Number+1)-


Within the function calculateAccelerationArray, Velocity and Time don't exist, they only exist within main(), where they are of type double. I think you mean:

1
2
a = (v.at(Number+1)-v.at(Number))/(t.at(Number+1)/(t.at
                 (Number+1)-t.at(Number-1));






main.cpp:62:11: error: no match for ‘operator=’ (operand types are ‘std::vector<double>’ and
‘__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type {aka double}’)

         a = (v.at(Number+1)-v.at(Number))/(t.at(Number+1)-


a is a std::vector<double>. You are trying to assign a double to it, because your equation returns a double.
You are probably meaning to set an element of a to that double, for example:

a[Number] = (v.at(Number+1)-v.at(Number))/(t.at(Number+1)/(t.at(Number+1)-t.at(Number-1));




main.cpp:65:14: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka
std::basic_ostream<char>}’ and ‘std::vector<double>’)

         cout << a << "    " << p << endl;


Again, a is a std::vector<double>, you can't just throw it into an ostream like that. A clean way to do so:

1
2
3
4
5
#include <iterator>
#include <algorithm>

std::ostream_iterator ostr_it(std::cout, " "); //delimit vector elements by spaces
std::copy(a.begin(), a.end(), ostr_it); //copy vector elements to the ostream 



main.cpp: At global scope:

main.cpp:85:1: error: expected unqualified-id before ‘{’ token


You need to remove the semicolon a the end of displayAcceleration()'s declarator:

1
2
void displayAcceleration(vector<double> t, vector<double> p, vector<double> v, 
vector<double> a); //<-- remove this semicolon 



That should already improve things significantly. Please note that you made the same errors in multiple places sometimes, so keep that in mind.

Hope that helps. please do let us know if you require any further help. Also, when possible,please include any compiler errors you are getting, that makes it a little bit easier for us to help you.

All the best,
NwN

Last edited on
NwN,

I am sorry about the compiler errors. I will include those in the future. You are right, there were a lot of errors. The corrections you provided cleared up almost all my errors.

main.cpp:65:14: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<double>’)

cout << a << " " << p << endl;

Again, a is a std::vector<double>, you can't just throw it into an ostream like that. A clean way to do so:
1
2
3
4
5
6
#include <iterator>
#include <algorithm>

std::ostream_iterator ostr_it(std::cout, " "); //delimit vector elements by spaces
std::copy(a.begin(), a.end(), ostr_it); //copy vector elements to the ostream 
 



I tried using this. I am not familiar with iterators, but have done some reading today. My basic understanding of this is that we are trying to the spaces into vectors, I think?

Anyways, I tried inputting this code just below my includes, and inside my declarator [void calculateAccelerationArray(vector<double> t, vector<double>& p, vector<double> v, vector<double>& a)]

I keep getting two errors:
F:\*.cpp|19|error: invalid use of template-name 'std::ostream_iterator' without an argument list|
F:\*.cpp|20|error: expected constructor, destructor, or type conversion before '(' token|


I was wondering if this may be due to the compiler I am using. I have Code::Blocks 98.
std::ostream_iterator is a template class and you must supply the type of the variable you are inserting into the stream when you define a std::ostream_iterator.

std::ostream_iterator<double> ostr_it(std::cout, " ") ;
Last edited on
Thank you for your quick reply!

Here is my input file data. The "---" are added to separate the numbers in this window. They should not normally be there.

Time(Sec) ---Velocity (m/s)
0 ---0
0.1 ---0
0.2 ---0
0.3 ---0.016532735
0.4 ---0.091686478
0.5 ---0.391340578
0.6 ---1.014768606
0.7 ---2.196126032
0.8 ---3.871247372
0.9 --5.789352979
1 ---7.716825525
1.1 ---9.490237052
1.2 ---11.3509455
1.3 ---13.21353105

 Number    TIME      Velocity
   1       0       0
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Process returned 3 (0x3)   execution time : 1.732 s
Press any key to continue.


In reading some other threads about this output message, I think it might have something to do with my v.at() and t.at() vectors not being initialized. If that's the case, how would I do that? I have to initialize the vectors values in the int main because that's where I retrieve my input data, right?
I have also changed my Number value to start at 1 in my for loop.
for (Number=1;Number<=t.size();Number++)
I am still getting the range error... any suggestions?
closed account (o3hC5Di1)
Hi there,

std::vector::at() will throw the std::out_of_range exception when you try to access an index that is not set (i.e. out of the vector bounds).

Some points in your code to consider:

for (Number=0;Number<=t.size();Number++)

Vectors are zero-indexed, that means the first element is vector[0] and the last is at vector[ vector.size()-1 ].
This means that vector[ vector.size() ] will be out of range, so you will want to do:

for (Number=0;Number<t.size();Number++)



Also, within that for loop:

at(Number+1)

Nothing guarantees that Number+1 will be in range. If Number==vector.size()-1, Number+1 will be out of range.

All the best,
NwN



NwN,

I greatly appreciate your help with this.

I am still getting the same error though.
1
2
        a = (Velocity.at(Number+1)-Velocity.at(Number))/(Time.at(Number+1)-
             Time.at(Number));


When this line starts, thats where I get my out of range. It doesn't matter what Number actually is. That is the first line. It is not even near my vector size limit of 174.
1
2
3
4
5
6
7
8
9
10
 while (!Rocket_Data_Input.eof()) // Takes data from input file.
    {
    Rocket_Data_Input >> Time >> Velocity;
    for (Number=0;Number<=t.size();Number++);
    cout << "   " << left << setw(5) << Number << "   " << left << setw(8) <<
         Time << left << setprecision(12) << setw(16) << Velocity << endl;
    t.push_back(Time);
    v.push_back(Velocity);
    calculateAccelerationArray(t, p, v, a);
    }
Could it be doing this because in my int main I push_back the vector and don't have the vector fully developed yet?
I think the most likely reason is because you didn't change the if (Number = 1) not to be assignment in calculateAccelerationArray (line 60 in the OP - also mentioned by NwN.) If so, please pay attention to the warnings generated by your compiler. If there aren't any, turn your warning levels up.

You can remove line 4 in code in the previous post. It is the effectively the same as: Number = t.size()+1;. This doesn't actually affect your code except for the output on line 5 in the same code, since Number is assigned a new value before it is used in calculateAccelerationArray.
Last edited on
closed account (o3hC5Di1)
Hi there,

You're most welcome.Do you happen to know which part (ie on which vector) you are getting the error?

In the for loop of your calculationAccelerationArray function, you are running Number until it is smaller than t.size(). However, you're using Number as an index on other vectors (like a and p), so if they are not of the same size as t, an exception will be thrown.

If you have gdb debugger available to debug your program, you could try some of the following:

# gdb ./program
gdb> catch throw
gdb> run


It will interrupt the program at the point where the exception is thrown. Then using the "step" and "print" commands you can precisely find out where the program goes wrong.

All the best,
NwN
Last edited on
Thank you, I will have to remember that for the future. I spent a long time working at school today and my teacher helped me fix my program. I had to change pretty much the whole thing, so I am not sure what the actual solution is. I appreciate all your help!
closed account (o3hC5Di1)
It's a shame that your teacher didn't help you in a way that you actually understand your mistakes and the actual solution, after all, that's her job. Feel free to post the new code with any questions you might have though.

All the best,
NwN
Topic archived. No new replies allowed.