Analyse a beam

Pages: 123
I’m not sure which section I should put this in. I’m just starting to learn C++ after many years of using various BASIC languages. I have often looked at C and C++ but hated the braces and so didn’t get my feet wet. Most tutorials for computer languages seem to revolve around subjects that have little interest to me, so invariably I use the same format to get me into the language: I develop a program for designing a simply supported beam. This requires input and output, variables of different types, arrays, loops, conditionals such as if..else and case(switch) and so on. So it gives me a reasonable grounding.

I’ve produced a program in C++, which has been converted from a BASIC program. This, I think, can be seen from its content. Since I have only just started, it doesn’t contain any classes or structs, or for that matter functions (other than main()). I have included the code to demonstrate what can be done at any early stage of learning. However, the program might be of interest to Structural/Civil Engineers, Architects and Builders. My intention would be to develop it further, both in a more advanced structure and also so that it can be used in developing reinforced concrete and steel beams. I did this many years ago using BASIC and this was used by the Architect I worked for to submit calculations to the local authority. However, standards have moved on a lot since then!

I'll submit the program in another submission


Rather than making multiple separate threads - simply reply to this one.

Hint on pasting code:

[code]your code here[/code]
I did try but the code brackets on the input box didn't work. Can I just type it in as you have done above. It was messy setting up 3 postings. There you go it works this time!. Would it be better if I tried again and deleted the three postings I have made?
You can delete your own posts if you wish - if there are no other replies, the entire thread should disappear.

As for code tags, yes you can type them in yourself rather than clicking on a button if you wish. I think there are some forum bugs which cause glitches on new posts, but you can re-edit the post to add tags if necessary.
> I’m not sure which section I should put this in. I’m just starting to learn C++
Beginners may be a good place.


> I’ve produced a program in C++, which has been converted from a BASIC program. This, I think, can be seen from its content.
two things: there is no 8 character limits on variable names, use meaningful names; and array index goes from 0 to size-1, outside that is an invalid access, however the program may not crash.
Thank you. You are correct in that I should use meaningful names, which strangely I did with the BASIC programs (BASIC has moved on a lot since the early days of single character variables). The reason I didn't do it here, is that I went right back to the original BASIC program to convert and used many of the variables from there. Lazy I know, but I will change it as I progress the program.

I have now changed the size of the arrays to (n+1) to allow for the first subscript being 0. I am surprised that the program didn't crash. It really should have done with some of the examples I tried.

I prefer to use (1 to n) because it is much clearer to me when dealing with structures (building construction structures). To clarify, the number sections being considered on the beam is say 21, I use n[1 to 21], otherwise it becomes confusing.

But thank you for the clarifications. I'm grateful for all the help I can get.

Hello @RNBW,

It's good to see C++ being used for structural analysis - I think it is going to be much more useful, powerful and widely used than something in BASIC. Just some comments (and I'm referring to your code in other threads, I know). Some of these comments have already been made, but they tend to go together.

- It's very difficult to read without the formatting imposed by code tags.
- Meaningful variable names: whilst a civil engineer will use S for shear force, M for bending moments and RL and RR for right and left reactions, you will make it much more generally readable if you use more informative names.
- Break it down into small functions - there's a lot of repetition.
- Consider file input and output. It takes quite a long time (and a lot of repetition) to reply to all the input questions. Minor changes are easily made in an input file.

There's some civil-engineering aspects too (and yes, I have written a beam analyser for work purposes, albeit in javascript rather than C++):
- You appear (from your calculation of second-moment of area) to have restricted yourself to solid rectangular sections. Most beams designed to resist shear and bending are I-beams. You could just input the section parameter EI and then it will apply to any beam cross section.
- Although you have 4 load cases (point load, UDL, the two triangular loads) you could easily reduce this to 2: the point loads (W) and continuous loads defined by the load density at the two ends (wl and wr) - this automatically encompasses all of cases 2,3,4.
- You seem to have a numerical-integration routine in, but none of your load cases need it: there are analytical (low-order polynomial) solutions for all of them.
- A useful output from your program would be beam deflections - you should be able to get these once you have the bending-moment distribution.

Good to see engineering examples!
as a long term go between (I worked for many years with aerospace engineers), I will argue that your names ARE meaningful. I will argue that math code should look like the math it represents. If that means one letter variables, that is FINE. The engineer can read it and debug it easier.

Its just fine to say
e = m*c*c;

spelling them out isn't helpful, and when you have big equations, its actually harmful as it becomes unpossible to read and debug. When it looks almost exactly like the textbook form, its much easier to spot a mistake.

Use meaningful variable names, yes, I never said not to. I am saying, in the context, the names ARE meaningful as-is.



Thank you lastchance, that's very constructive. I've already started working on meaningful names and I'll consider the other points you have made as I learn a bit more about C++ and introduce functions, etc.

What do you mean "formatting imposed by code tags"?

I only show a rectangular section so that I have something to produce a second moment of area to be able to calculate deflection. The numerical integration I have included is based on Simpson's Rule and integrates the bending moments to produce deflections.

I hope to develop the program to include design for reinforced concrete and steel beams, which will have various sections. The EI calculation will take place within the body of this part out the program and will no longer be required early in the program.

One of the things I will have to do is to find out how to produce hard copy of the output.

I'm glad to see someone else out there with an interest in engineering calculations. Maybe interest could be drummed up from a few more to put forward ideas!
closed account (48T7M4Gy)
@RNBW
As already requested please restrict the activity on this to a single thread - this one. The reason is to avoid duplicated effort and crossed wires. You can close them down by 'green ticking' them. A green tick indicates that that particular thread is resolved.

As far as your programs are concerned it comes at a good time for me because of other things I am doing. The way I plan to tackle the SFD tabulation is along the lines below and incorporate it in into a frame analysis program. It's a first pass so you can tell me about any bloopers. As you know, because of the discontinuities in the plot, simple beam equations aren't much use.

I also noticed you appear to be using Simpson's rule to integrate for moments and then deflections and, I might be wrong, but I get the impression that's why the number of beam segments has to be odd (or even?). If that's the reason, while it's only a small point, I'd scrap it.

1. Good and meaningful names are absolutely vital as part of good modern software practice particularly for proper planning, self-documentation, debugging, and future maintainability. A lot of engineering code is legacy code and suffers the pitfalls of the 'old days' when memory was scarce, unstructured spaghetti code was the way and processing power was nothing like it is today.

( I noticed E = m*c^2 commented on above. Nobody would suggest anything other than that in a simple physics program of a few lines but for readability and potential conflicts that sort of simplicity could quickly become a complete disaster.)
(Stroustrup has recently written coding standards for the Joint Strike Fighter software - that will give you a good idea what aerospace software state of the art is all about.)

2. While I fully understand the challenges going from Basic to C++ use it as an opportunity. You are going in a very positive direction using C++.

3. One of the most powerful aspects of C++ with direct application to your stuff is STL containers, something you need to spend time on as part of the learning curve. <vectors> are the way - not arrays!

4. The tutorials here are worth spending time on. Looks daunting maybe but well worth a few months part time with persistence. http://www.cplusplus.com/doc/

5. One of the things that stands out to experienced programmers is the opportunity for using functions and classes to reduce repetition especially. Leave that for later but definitely put it on the todo list. As an example, the SF vector can be passed around to all sorts of integrations and displays. Similarly additional load cases of any/all types can be combined and processed individually or as aggregates.
Last edited on
There is a happy medium of course. What you did looks great, Ra, Rb, dx look good like good, descriptive names to me in the context.

closed account (48T7M4Gy)

4.9.1 Naming Identifiers
The choice of identifier names should:
• Suggest the usage of the identifier.
• Consist of a descriptive name that is short yet meaningful.
• Be long enough to avoid name conflicts, but not excessive in length.
• Include abbreviations that are generally accepted.
Note: In general, the above guidelines should be followed. However, conventional usageof simple identifiers (i, x, y, p, etc.) in small scopes can lead to cleaner code and will therefore be permitted.
Additionally, the term ‘word’ in the following naming convention rules may be used to refer to a word, an acronym, an abbreviation, or a number.

JOINT STRIKE FIGHTER
AIR VEHICLE
C++ CODING STANDARDS
FOR THE SYSTEM DEVELOPMENT AND DEMONSTRATION PROGRAM Document Number 2RDU00001 Rev C
December 2005
Last edited on
What do you mean "formatting imposed by code tags"?

If you use indentation to indicate your code structure - for example loops, if-blocks etc (see Kemort's code for an example) - then putting it within code blocks as @Chervil shows near the top of this thread preserves that indentation. Otherwise everything on the web comes out squashed against the left-hand side and it is hard to follow code structure. You should definitely be using indentation.

We'll beg to differ over variable naming; I think Kemort's SF for shear force, Ra and Rb for end reactions are a good compromise. I would probably use BM for bending moment. Engineers have vigorous debates about sign conventions (and @Kemort's direction for positive shear force is directly opposite to the one I prefer; I'll live with it!)

how to produce hard copy of the output

I strongly suggest that you learn to use file output (see http://www.cplusplus.com/doc/tutorial/files/). Then you can plot your output with any simple plotting package (I'd go for gnuplot for its sheer simplicity; or you can use Excel, Matlab or any other tool.) If you also use file input then it will save you having to do lots of typing in every time you make small changes to your code and re-run it. (For basic testing, you could temporarily hard-code your input variables.)

The numerical integration I have included is based on Simpson's Rule and integrates the bending moments to produce deflections.

It's hard to see from your code exactly what you are doing here. However, unless you are short-cutting this in some way that I haven't realised, then you have to integrate TWICE to get from bending moments to deflections: the equation is
EI.d2y/dx2 = -M
(where y is downward deflection, M is bending moment and I'm using a sign convention with M anticlockwise positive on the right hand end of a cut). Moreover, your boundary conditions (for a simply-supported beam) are on y and not dy/dx, so for non-symmetric cases you will have to complete both integrations before you can fix the free constants.

Be careful with units. I note that your Young's modulus is entered in N/mm2, your bending moment in kN.m and you have a pow(10,12) conversion factor knocking around. I think you might be a lot safer working in SI base units of N and m and letting engineering notation (eg 1.0e12) deal with the inevitable large numbers in the answers for real-world loads.
closed account (48T7M4Gy)
and @Kemort's direction for positive shear force is directly opposite to the one I prefer; I'll live with it!


Believe it or not I have no fixed (no pun) idea on this and paid no attention to it, other than getting the signs right, in what I did because structurally it doesn't matter as long as the convention, whatever it is, is consistent and understood.

I agree, the integration is twice a la 'slope-deflection'.

File usage for input/output is pretty much mandatory - txt files for data and text output shoved into an OS text editor solve printing problems and also provide input into GUI text boxes.

Windows/VStudio, Code::Blocks and Qt also seem to have all the graph capabilities as an alternative to excel, gnuplot, sage etc provided there's time/interest to write the code.

I hope @RNBW hasn't blown a fuse and retreated to Basic :)
> One of the things I will have to do is to find out how to produce hard copy of the output.
stream redirection. Your program reads from standard input/output (cin/cout), and when executing it you may do
$ ./program.bin < input > output 2> error.log
now it gets its input from the `input' file, it outputs to `output' and send error messages to `error.log'.

However, you still should learn about c++ files.



> Its just fine to say
> e = m*c*c;
I'll say that energy = mass*c*c; is better.

> double Ra = 0.0, Rb = 0.0; // Reactions
> Ra, Rb, dx look good like good, descriptive names to me in the context.
still, he felt the need to put that comment. ¿What about `reaction_{a,b}' or `reaction_{begin,end}'?

meh, splitting hairs at this point.
@kemort/@ne555/@lastchance/@jonnin

Thank you very much for your constructive comments.

In respect of naming variables, I think it is a case of horses for courses. Structural and Civil Engineers will be well aware of the formulae and the terminology used normally in their calculations, so in this respect it will be clearer to them to use such simple single or double letter variable names. Outside this then meaningful longer names may be necessary.
closed account (48T7M4Gy)
@RNBW So there you go! I can't speak for others here but it looks like the depths of comment have been plumbed.

Please feel free to post your latest updates. Good luck with it. :)
@kemort

I've just had a look at the code that you provided and it's way beyond my capabilities at the moment and I will have to do a lot of looking up and practicing before I could incorporate any of it. Something for the future.

I hope you are wrong and that I do get further comment. The wider the audience the better.

Thanks for your help.
@dhayden
I also get the compiler report that variable k1 is unused, but I don't know why. It is used in the Numerical Integration routine used to calculate deflection.
@lastchance/@kemort
There seems to be some confusion about how deflections are being calculated. Double Integration is one of the many ways to calculate deflection. Using Simpson's Rule is another.

The method of analysis uses the flexibility equations and a process of numerical integration applying Simpson's Rule.

At any point along the beam

deflection = Integral (ms.mx/EI) dx

(sorry I couldn't see how to show integral figure properly)

where
ms (in the program ms[]) is the bending moment along the span due to the applied loads
mx is the corresponding bending moment due to a unit load applied at the point where the deflection is being calculated.

Applying Simpson's Rule to the numerical integration to achieve greater accuracy gives

Integral ydx = s/3[(sum of end ordinates)+4(sum of even ordinates)+2(sum of odd ordinates)]

where s = the length of each increment (e.g. in a 20m span with 21 sections being considered), s = span/20 = 1m.

The accuracy of the method can be easily checked.
For a point load, deflection at mid-span = WL^3/48EI, and
for a full span udl, deflection at mid-span = 5WL^3/384EI

For the following criteria for a point load, using the formula:
No of Section = 21
Span = 20m, W= 30kN, Distance from left reaction to load = span/2 = 10m
E = 25000. Beam size 400mm x 600mm deep.
Deflection = 27 .78mm
The program gives a deflection of 27.78mm

For the following criteria for a full span UDL, using the formula:
No of Section = 21
Span = 20m, W= 50kN, Distance from left reaction to start of load = 0m
Length of load = 20m
E = 25000. Beam size 400mm x 600mm deep.
Deflection = 28.94mm
The program gives a deflection of 28.94mm

The deflections calculated will not always be exactly equal, but will always be very close, within acceptable tolerances.

The reason that Simpson's Rule has been used rather than a more mathematical system is that it is easily demonstrated by hand and also semi-graphically.

When I wrote my first beam analysis many years ago (using an Amstrad CPC computer and Amstrad BASIC) the output of the program onto a calculation sheet was readily accepted by every local authority without having to submit the computer program for local authority approval before allowing its use. The Architect I worked for used the program long after I moved on, until adoption of Limit State design prevented its continued use. This is why it is important to me to be able to direct output to both screen and printer. With BASIC it was easy. Not so easy with C++.

Below is s snippet from the program relating to deflection calculation, to which I have added further comments to try to clarify.

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
           //-----------------------------------------------
           //  CALCULATE DEFLECTIONS AT SECTIONS ALONG BEAM
           //-----------------------------------------------
           // Deflection = Integral (ms[k1].mx)/EI dx
           
           // Simpson's Rule:
           // Integral ydx = (s/3).[(Sum of end ordinates +
           // 4(sum of even ordinates) + 2(sum of odd ordinates)]
           // where s = length of increment between sections considered.
           // i.e. for 20m span with 21 sections s = 20/(21-1) = 1.                          

           //SET UP SIMPSONS' ORDINATES AS SIMPSON'S RULE
           // Must be an even number of spaces (21 sections: 20 spaces)
           // If section is an even number then multiplier s[k1] of
           // BM due to Unit Load is 4. If it is odd number
           // multiplier is 2.
            s1[1] = 0;
            s1[ns] = 0;
            for (int k = 2;k<=ns;++k) {
               if(k % 2 == 0) {        // check for even number
                  s1[k] = 4;
               }
               else {
                  s1[k] = 2;    // if not even number, it is odd number
               }
            }

            //NUMERICAL INTEGRATION

            for (int k=1; k <= ns; ++k) {
               dk = 0;
               zd = (k-1) * L/(ns-1);
               for(int k1  = 1; k1 <= ns; ++k1) {
                   // UNIT LOAD MOMENTS
                   // Set up and calculate moments due to
                   // Unit Loads at relevant sections
                   // along the beam
                   z = (k1 - 1) * L/(ns-1);

                   if(z<=zd) {
                      mx = z * (L - zd)/L;
                   }
                   else {
                     if(z>zd) {
                        mx = zd * (L - z)/L;
                     }
                   }

                   // SUMMING MOMENT PRODUCTS AND SIMPSONS' ORDINATES
                   // Multiply BM at sections by BM due to Unit Load
                   // at each section
                   dk = dk + ms[k1] * mx * s1[k1];
                   }      // end of scope for loop k1

                  ds[k] = dk * L * pow(10,12)/(ns-1)/3/i2/ec;

            }  // end of scope for loop k

            //SORT FOR MAXIMUM DEFLECTION AND ITS LOCATION
            for(int k = 1; k <= ns; ++k) {
               if (ds[k] > dm) {
                  dm = ds[k];
                  sd = L * (k - 1)/(ns-1);
               }
            }        // end of scope for loop k for sort max deflection 


I hope this clears up some of the background to the program design.
Last edited on
Pages: 123