# Monthly Archives: May 2012

## The Step response of an RLC circuit in State Space Model

In this post we will see the step response of an RLC circuit using a matlab program.The initial conditions are current is 1ma and voltage across capacitor is 2V.

The state space representation of the above circuit is.

Here R =4.1K, L=1.7H and C=1 F

A=[-241.76 -.588;10^7 0] % this is the matrix A
B=[1;0]                  % this is the matrix B
C=[0 1]                  % this is the matrix C
D=0                      % this is the matrix D
sys=ss(A,B,C,D)          % ss() is a function to form the state space
t=0:.00001:.01;          % take several time samples
for i=1:1:1001           % make an input matrix of desired length
u(i)=10;
end
[y,t,z]=lsim(sys,u,t,[10^-3 2])% in this function the variable y has output values
%t has time values and z has the values of state space variable
plot(z(:,1)) %plot the values of X1 which is first state space variable

% using full colon means all values to be more clear z(:,1) means all rows of first column
title(‘state 1’)
plot(z(:,2))
title(‘state 2’)

## Lead Compensator design with Root Locus

The steps to design the Lead Compensator are with root locus are:

1. From given specifications determine the damping ratio and the natural frequency .
2. Find the dominant pole
. If damping ratio alone is given then draw the root locus and draw line from origin at an angle to intersect the root locus, the point of intersection is the dominant pole.
3. Measure angle contributed by each pole and zero of uncompensated system to the dominant pole as marked in the diagram, the angles are measured in the counter clockwise direction from the positive real axis direction.
4. The angle needed to be provided byt the compensator is
This angle if greater than 60 then two compensators each providing half the required angle is made.
5. as In the figure above draw PC bisection angle APO and draw line PB and PD such that they make angle with respect to PC B is the required pole and D is the required zero.
6. a lead compensator has the form
7. Determine open Loop gain K at Sd,by taking equation

8. form the complete transfer function with the lead compensator added in series to the original system
9. plot the new Bode plot and determine phase margin and observe that it is the required phase margin

Now to do this In Matlab let us take a question. I will be solving the question number 1.7 in Advanced Control Systems By Nagoor Kani. In th text book the question has been solved without using matlab you can go through it to understand the steps better.

The question is
the Peak over shot is 12.63% natural frequency of oscillation is 8 rad/sec and velocity error constant should be greater than or equal to 2.5.

Solution:

Calculate the damping ration from the peak over shoot given the equation had been discussed in the previous post.

The code below shows the matlab commands to obtain the design.

clear all
close all
n=input('Enter the Coefficients of Numerator')
d=input('Enter the Coefficients of Denominator') %enter as array [1 11 28 0]
'G(s)'
G1=tf(n,d)
G2=tf(conv([1 0],n),d); % this is for evaluating the Kv we multiply numerator with s.
M=input('Enter peak overshoot: ')
z=sqrt(log(M)^2 /(pi^2 + log(M)^2)) % calulate damping ratio
wn=input('Enter wn: ')
Kv=input('Enter velocity constant: ')
Sd=complex((-z*wn),(wn*sqrt(1-z^2))) % forming the dominant pole
rlocus(G1)  % plotting uncompensated root locus
hold on
plot(Sd,'*') % mark the dominant pole
axis([-20 20 -20 20])
'Press any key to proceeed'
pause
close all
pzmap(G1)  % make pole zero plot.
hold on
plot(Sd,'*')  % mark the dominant pole
plot(conj(Sd),'*')
axis([-20 20 -20 20])
Po=roots(d)
pang=zeros(1,size(Po,1));

% Finding the angle contributions of poles
for i=1:size(Po,1)
pang(i)=abs(atand((abs(imag(Sd))-abs(imag(Po(i,1))))/(abs(real(Sd))-abs(real(Po(i,1))))));
if(real(Po(i,1))>real(Sd))
pang(i)=180-pang(i);
end
end
Zo=roots(n);
zang=zeros(1,size(Zo,1));

% Finding the angle contributions of zeroes
for i=1:size(Zo,1)
zang(i)=abs(atand((abs(imag(Sd))-abs(imag(Zo(i,1))))/(abs(real(Sd))-abs(real(Zo(i,1))))));
if(real(Zo(i,1))>real(Sd))
zang(i)=180-zang(i);
end
end

thetap=sum(pang);
thetaz=sum(zang);
phm=thetap-thetaz-180
phmh=phm;
t=1;

% LOGIC TO CHECK IF PHASE LEAD IS GREATER THAN 60 in some cases it can be 4 times greater than 60 then we have to repeatedly divide it till less than 60
while phmh>60
phmh=phm/(2*t)
t=t+1;
end
t=2*(t-1);
ph1=180-atand(abs(imag(Sd))/abs(real(Sd)));
ph1=ph1/2;
c=(real(Sd))-((imag(Sd))/tand(ph1));
ph=ph1-(phmh);
pol=(real(Sd))-((imag(Sd))/tand(ph))
ph=(ph+phmh);
zer=(real(Sd))-((imag(Sd))/tand(ph))
‘Press any key to proceeed’
pause
Gc=tf([1 -zer],[1,-pol])
hold off
‘Open Loop Transfer Function K=1′
if phmh==phm
Go=Gc*G1;
sG=Gc*G2; % For evaluating error constant
else
Go=(Gc^t)*G1
sG=(Gc^t)*G2 % For evaluating error constant
end
sG=minreal(sG); % For evaluating error constant
rlocus(Go)
hold on
plot(Sd,’*’)
axis([-20 20 -20 20])
[K a]=rlocfind(Go)

‘The Velocity Error Constant is’
Kvn=dcgain(K*sG); % For evaluating error constant
if Kvn>=Kv
‘Condition is satisfied’
Kvn
else
‘Improve design’
Kvn
end
‘The Complete transfer open loop function’
Go=Go*K
close all
rlocus(Go)
hold on
plot(Sd,’*’)

Root Locus Of uncompensated system the dominant Pole is not on Root Locus

Root Locus Of compensated system the dominant Pole is on Root Locus

## Lead Compensator design with Bode plot

The steps to design the Lead Compensator are:

1. Determine K from the error constants given
2. Sketch the bode plot
3. Determine phase margin
4. The amount of phase angle to be contributed by lead network is
, where is the required phase margin and is 5 initially. if the angle is greater than 60then we have to design the compensator as 2 cascade compensator with lead angle as
5. calculate
from bode plot find such that it is the frequency corresponding to the gain
6. calculate
7. a lead compensator has the form
8. form the complete transfer function with the lead compensator added in series to th original system
9. plot the new Bode plot and determine phase margin and observe that it is the required phase margin
10. if not satisfactory repeat steps from step 4 by changing value of by 5

Now to do this In Matlab let us take a question. I will be solving the question number 6.2 in Control Systems By Nagoor Kani. In the text book the question has been solved without using matlab you can go through it to understand the steps better.

The question is
the phase margin should be atleast 33 and velocity error constant is 30.

Solution:
The velocity error constant is

On solving we get K =9600

The code below shows the matlab commands to obtain the design.

clear all  % clear all variables
close all  % close all previous graphs
K=9600	% value of K calculated from error constants
G=tf(K,conv([1 4 0],[1 80])) % make the transfer function
[Gm,Pm]=margin(G) %get the gain margin and phase margin
margin(G) %plot the bode plot
Pd=input('Enter Desired Phase margin')
ep=input('Enter value e') % enter the value of epsilon initially start with 5
ph=Pd-Pm+ep
if ph>60   % check if angle needed is greater than 60
phm=ph/2
else
phm=ph
end

alpha=(1-sind(phm))/(1+sind(phm)) % calculate alpha
db=-20*log10(1/sqrt(alpha)) %calculate the gain in db
wm=input(‘Enter frequency’) % from plot obtain frequency corresponding to above gain
T=1/(wm*sqrt(alpha))
Gc=tf([1 1/T],[1 1/(alpha*T)]) % form transfer function of compensator
‘Open Loop Transfer Function is’
if ph==phm
‘Single’
Go=Gc*G/alpha
else
Go=Gc*Gc*G
%if angle was greater than 60 we designed compensator for half value so we cascade them and their attenuation is not nullified and should be retained
end

margin(Go)
pause
comp=feedback(Go,1,-1);
uncomp=feedback(G,1,-1);
step(uncomp) % observe step response
hold on
step(comp)
legend(‘Uncompensated’,’Compensated’)

Step response of compensated and Uncompensated system

## Lag Compensator design with Root Locus

So far we have discussed on an Introduction to Matlab and Lag compensator design with bode plot. In this post we will deal with lag compensator design with time domain specifications and using the root locus technique.

The steps to design the lag Compensator are

1. Draw the root locus of the given open loop uncompensated system with K=1
2. From given specifications determine  the damping ratio.
3. Draw a line from origin making an angle with the negative real axis. The point of intersection of that line with root locus gives the dominant pole Sd
4. Determine open Loop gain K at Sd,by taking equation

5. Let Kv velocity constatn for uncompensated system, Kvd=Desired velocity Constant
6. A=Kvd/Kv and

7. 1/T is always choosen to be 10%of second pole of uncompensated system.
8. a lag compensator has the form
9. form the complete transfer function with the lag compensator added in series to th original system
10. plot the new Root locus and check if given conditions are satisfied. Or else change the location of poles.

We will solve question number 1.3 in Advanced Control Systems By Nagoor Kani. Let us solve this with matlab.

The question is Forward ath transfer function of a unity feedback control system is
. Design a lag compensator so that peak overshoot is less than 16% for step input and steady state error is less than 0.125 for ramp input.

Solution:
The percentage overshoot is given to determine the damping ratio and we can use the relation

The code below shows the matlab commands to obtain the design.

n=1 %taking K=1
d=conv([1 0],conv([1 2],[1 8]))
'G(s)' % Display title G(s)
G=tf(n,d)
rlocus(G) % plot root locus of uncompensated system
M=input('Enter Percentage overshoot')
zeta=sqrt(log(M)^2 /(pi^2 + log(M)^2)) % calulate damping ratio
sgrid(zeta,0) % draw line from origin with angle of cos^(-1) zeta
[K p]=rlocfind(G) % find the gain K at the point of Sd , Sd selected by clicking on the graph
Kvu=input('Enter Uncompensated Vel VConst')
Kvd=1/ess
A=Kvd/Kvu;
Beta=1.2*A;
root=roots(d); finding roots of the denominator
T=1/(-0.1*root(2)) % usinthe second root
Zc=1/T
Pc=1/(Beta*T)
Gc=tf([1 Zc],[1,Pc])
sys=Gc*G*K
rlocus(sys) % plot root locus of compensated system
pause
sys=feedback(sys,1,-1)
step(sys)
hold on
G=feedback(G,1,-1)
step(G)

The Diagrams below show the results obtained Please don’t forget to comment or ask doubts in case of trouble.

Uncompensated system root locus

Root Locus of Compensated System

Step response of Compensated and Uncompensated system

## Lag Compensator design with Bode plot

In the previous post  An Introduction to compensator Design with matlab we saw an introduction to compensators. In this post we will deal with lag compensator design with frequency domain specifications.

The steps to design the lag Compensator are

1. Determine K from the error constatns given
2. Sketch the bode plot
3. Determine phase margin if it is not satisfactory design lag compensator
4. take  as the required phase margin to that add a tolerance of 5 so that new phase margin is
5. Find new gain cross over frequency which is the frequency corresponding to of previous step for that find
from the bode plot determine corresponding to
6. Determine gain corresponding to from bode plotlet it be A db
7. a lag compensator has the form

8. since

9. form the complete transfer function with the lag compensator added in series to th original system
10. plot the new Bode plot and determine phase margin and observe that it is the required phase margin

Now to do this In Matlab let us take a question. I will be solving the question number 6.2 in Control Systems By Nagoor Kani. In th text book the question has been solved without using matlab you can go through it to understand the steps better.

### Open loop transfer function   and the phase margin should be atleast 33 and velocity error constant is 30.

Solution:
The velocity error constant is

On solving we get K =9600

The code below shows the matlab commands to obtain the design.

K=9600
d1=conv([1 4 0],[1 80]) % used to formulate the polynomial
G=tf(K,d1) % generate the transfer function.
margin(G)
pmreq=input('Enter Required Phase Margin') % enter 33 as given in question
pmreq=pmreq+5
phgcm=pmreq-180
wgcm=input('Enter new gain cross over frequency') % from the first bode plot use the mouse pointer and locate wgcm corresponding to phgcm.
[Beta,p]=bode(G,wgcm)
T=10/wgcm
Zc=1/T
Pc=1/(Beta*T)
Gc=tf([1 Zc],[1 Pc])
sys=Gc*G/Beta
margin(sys)

Uncompensated system

Matlab window

Identifying the new frequency

Compensated system

If you have any doubts please do contact me.

## An Introduction to compensator Design with matlab

This will be a series of posts where I will be dealing with Control system Compensator design using matlab. This is intended primarily for Btech Electrical and Electronics students.

I will try to be as brief as possible the underlying concepts have to be studied from standard text books.

If there are any mistakes please point them out.

Basically the compensators have to be designed based on the time domain specifications like rise time, maximum overshoot,damping ratio and settling time. these are the transient state specifications. And in frequency domain the transient state specifications are phase margin, gain margin, resonant peak and bandwidth.

The steady state responses in both cases are the error constants.

We will start with what compensators  are. Compensators are devices added to a  control system so that it meets the given specifications. They introduce poles and zeroes to the system.

The main types of compensators are the lag, lead and lag lead.

### Lag Compensator

A compensator that introduces a phase lag to an input signal is called a lag compensator. It improves the steady state performance of the system, but reduces the bandwidth and results in a slower transient response too. It is basically a low pass filter.

A compensator that introduces a phase lead to an input signal is called a lead compensator. It increases bandwidth and improves speed ofresponse but there is only a small change in the steady state response. It is basically a high pass  filter.

Please do refer text books for more details on compensators.

Compensators can be designed with time domain specifications and it is done using root locus technique and If frequency domain techniques are used then Bode plot is used( other frequency domain plots can also be used but here we deal with bode Plot).

Commonly used functions in matlab

tf – converts system representation from transfer function to “system” format. This format provides an efficient way to store and manipulate the system model, but does not allow direct access to the system’s numerator and denominator orpoles and zeros. The syntax to convert from transfer function to “system” format is:
sys = tf (num, den);
tfdata – converts system representation from “system” format back to transfer function format. The syntax (for single-input, single-output systems) is:
[num, den] = tf data(sys, v );

series – forms the series combination of 2 blocks to produce the equivalent transfer function. The output of block 1 is the input to block 2. The syntax for the function in transfer function and in “system” formats are:
[num, den] = series(num1, den1, num2, den2);
sys = series(sys1, sys2);

parallel – forms the parallel combination of 2 blocks to produce the equivalenttransfer function. The outputs of block 1 and block 2 are added together. The same input is applied to both block 1 and block 2. The syntax for the function in transfer function and in “system” formats are:
[num, den] = parallel(num1, den1, num2, den2);
sys = parallel(sys1, sys2);

feedback – forms the closed-loop system that has block 1 in the forward path and block 2 in the feedback path. The default configuration is for negative feedback. In the syntax example shown below, the −1 for negative feedback is shown explicitly. For positive feedback, a +1 would be used in the function’s input argument list. For unity feedback, num2 = den2 = 1. The syntax for the function in transfer function and in “system” formats are:
[num, den] = f eedback(num1, den1, num2, den2, −1);
sys = f eedback(sys1, sys2, −1);

cloop – forms the closed-loop system when unity feedback is used. This function is obsolete, but is still available in most MATLAB versions. It can only be used when the block in the feedback path is unity, and it can only be used with the system model expressed in transfer function form, not in “system” format. The syntax for the function is:
[num, den] = cloop(num1, den1, −1);

rlocus – computes and plots the root locus for a system, using an internally generated set of gain values. A user-specified vector of gain values can be included as an input argument if desired. Output arguments of closed-loop poles and the corresponding gain values can also be obtained. In this case, no plot is made. If the root locus plot for negative gain values is desired, a minus sign is placed in front of num or sys. The syntax for the function in transfer function and in “system” formats are:
rlocus(num, den);
rlocus(sys);

rlocfind – computes the gain and the corresponding closed-loop pole locations for a specified point on the root locus. A crosshair is made available to select a point on the root locus plot. The gain corresponding to that point is returned, as well as all the closed-loop poles for that gain. The syntax for the function in transfer function and in “system” formats are:
[K, poles] = rlocf ind(num, den);
[K, poles] = rlocf ind(sys);

Instead of graphically selecting a point, one or more desired closed-loop pole locations can be input to the function. The gains and closed-loop poles cor- responding to those specified pole locations are returned. No error message is given if the specified pole locations are not actually on the root locus for the system. The syntax for the function in transfer function and in “system” formats are:
[K, poles] = rlocf ind(num, den, P );
[K, poles] = rlocf ind(sys, P );

bode – computes the magnitude (absolute value) and phase (degrees) of a system evaluated on the jω axis. If no frequency vector is provided as an input argument, MATLAB selects a set of frequency values. If no output arguments are specified, the Bode plots are automatically made. If output arguments are specified, no plots are made. Specifying a frequency vector and output
arguments, the syntax for the function in transfer function and in “system” formats are:
[mag, ph] = bode(num, den, w);
[mag, ph] = bode(sys, w);

margin – computes the following measures of relative stability based on the frequency response of a system: gain margin (Gm), phase margin (Pm), phase crossover frequency (Wcg), gain crossover frequency (Wcp). These measures
provide information about how much perturbation to a system can be tolerated without becoming unstable and are often used as design specifications. If no frequency vector is included as an input argument, the values are computed
analytically from the transfer function. If a frequency vector is included, the values are obtained by searching the magnitude and phase arrays at those frequencies. If no output arguments are specified, Bode plots are made with the gain and phase margins shown on the plots. The syntax for the function in transfer function and in “system” formats are:
[Gm, P m, W cg, W cp] = margin(num, den);
[Gm, P m, W cg, W cp] = margin(sys);
[Gm, P m, W cg, W cp] = margin(mag, ph, w);
nyquist – computes the real and imaginary components of the frequency response of a system (rather than magnitude and phase). A frequency vector is an optional input argument. If no output arguments are specified, a plot of the imaginary part vs. the real part of the frequency response is plotted, and the s = −1 + j0 point is indicated on the plot. If output arguments are specified, the real and imaginary parts are returned, and no plot is made. The syntax for the function in transfer function and in “system” formats are:
[re, im] = nyquist(num, den, w);
[re, im] = nyquist(sys, w);

step – computes the unit step response for a system. A time vector is an optional input argument. The vector of values of the step response is an optional output argument. If no output argument is specified, a plot of the response is made. The syntax for the function in transfer function and in “system” formats are:
c = step(num, den, t);
c = step(sys, t);

If you have learned the basics then please move on to the next Post.

Lag Compensator design with Bode plot

Lag Compensator design with Root Locus

## Electrical Energy- A Modern Wonder

If someone asks you to list out some of the most important inventions that revolutionized the world, you may say, radio, computers, electricity, steam engine etc. The list of inventions is just countless and we cannot pick out the “best” because all are equally important.

But if someone asked me that question I would say electricity, not just because I am an electrical engineer, but because I believe its one of the most marvelous discoveries made by man a reason that made me choose the subject for Engineering.

Electricity changed the face of the earth it change the way everything works. It brought about a revolution in all spheres of technology.

As such electrical energy is something to be treated with respect and to be used judiciously. Energy Conservation is a hot topic nowadays.

So I just thought I will share some tips I have learned through out my engineering course.

The major step towards saving our electricity bill and thereby to save energy is to design a proper wiring system in our houses.

There is a trend nowadays to have power plugs every where necessarily and unnecessarily. And that increases the power demand of the house from the view-point of the supplier and you are likely to be charged for a three-phase supply. And in reality you may not even be using.

In India three-phase supply is given to consumers with a load more than 5KW.

The table below shows the some of the electric loads and there values. So you can now calculate the total load of your house and see how many unnecessary points you have.

Light Points 60W
Fan points 100 W
Plug Socket (5A) 100 W
Power Plugs( 15 A) 1000 W
Exhaust fans 100 W

Ensure that you do house wiring by an expert because faulty wiring can cause wastage of current and thereby increase your electricity bills.

Now for those who cannot do anything about the number of points, there are some simple techniques to save energy. first and foremost switch to energy-efficient lamps. Change all the incandescent lamps as this will not only improve lighting but also the temperature within your room. I believe everyone has switched onto to CFL nowadays. I have never see any incandescent lamps recently.

The most important step is to turn off any equipment big or small that is not in use. Avoid unnecessary usage of electricity. Open windows whenever possible at daytime and reduce the use of lights and fans.

There is a tendency for us to leave remote controlled devices like the TV plugged on and switched off with the remote. Even when the TV is switched of by remote it consume around 10W of energy. Now if you leave it like that for 100 hours you will be utilizing 1 unit of energy( 1 Kwh).

Try to buy equipments with the 5 star energy efficiency ratings. The more number of stars the more energy you save.

So please use energy efficiently and effectively.

## An Engineer’s Hobby

After four years of my Btech life and the numerous electronics projects I did, I found my room overwhelming with broken components and fried up chips, all adding to the great e-waste. I had many ICs including a Pentium 4 processor some micro controller chips and even a DDR RAM. I felt like my room was a junkyard. My DDR RAM was in working condition so I tried to sell it to some of my friends and it is then that I realized that no one right now has a motherboard supporting the DDR. All have been upgraded to DDR2 and DDR3. It was then that i thought of “collecting electronic parts”, who knows the components that I have now may go out of production as newer technologies are invented, and this will also help in educating myself more about each component. I searched the Internet and i was disappointed not to find anything related to it. So maybe a new hobby was being invented. First I started by sticking the components on to a notebook and writing down its details just like a scrap book but soon I found out that it was not a practical solution as bigger components would not go into the book. Then I decided on Putting the components in resealable plastic covers and labeling them and I could keep a catalog on each component I have and collect useful information about it and write it down in a book.

P4 Chip and a Microcontroller

If any of my readers have suggestions about such a collection or if you know anyone doing such a thing please let me know. Because I would really like to do this in a good way. This is my small way of saving the world from e waste because if anyone else gets inspired by my blog they too will start collecting electronic items instead of just dumping them. Please don’t forget to give m your valuable suggestions. Making art out of electronics can be another way, I once tried my hand at that and here is something I made.

E-Man

## Classification Of Software Bugs

Who is not afraid of bugs ? Most of my readers I know will shudder just at the thought of those creepy things crawling all over you .

Just like the tag line of the Movie Eight-Legged Freaks , “Do you hate spiders? Do you REALLY hate spiders? Well they don’t like you either”

But there is another class of bugs that can ruin your sleep, your peace of mind and can really make you go nuts, we engineers call the software bugs. They can make a beautiful program a mess and can get you right back to square one. Everyone who has written a program no matter how basic it is will have encountered bugs in the first trial. Bugs can be caused due to carelessness from the part of the programmer or the programmers inability to spot out an invalid condition and it can also be caused by hardware imperfections.

No matter how much care is taken to write a bug free software is an unrealized dream and software experts claim that it will remain unrealized. Software Bugs have caused alot of trouble. Paul Bourdeaux mentions Top Ten Most Infamous Software Bugs Of All Time in his blog.

“Debugging is like removing needles from the haystack” It can be one heck of a job to find bugs in a very large program. While working on my Btech Project I encountered a Similar situation the program started giving weird results I spent almost two days checking the logic and analyzing it and the real cause of the error was a wrong argument to a function.

Despite all this There has been an effort to classify bugs in an interesting way. All those who have learned programming might have heard terms like run time errors, Logical bugs, arithmetic bugs, syntax errors etc.

But there is another classification of bugs and these are :

#### Bohrbug

A BohrBug is just your average, straight-forward bug. Simple like the Bohr model of the atom: A small sphere. You push it, it moves. BohrBugs are reproducible, and hence are easily fixed once discovered. These are named after Niels Bohr, who proposed a simple and easy-to-understand atomic model in 1913. In Bohr’s model, things like the path and momentum of an electron in an atom are predictable.

#### Heisenbug

A bug that disappears or alters its behavior when one attempts to probe or isolate it. No matter how much time and effort is spent trying to reproduce the problem, the bug eludes us. Such bugs were named Heisenbugs, after Werner Heisenberg, who is known for his “uncertainty principle”. According to his theory, it is not possible to accurately or certainly determine the position and velocity of an electron in an atom at a particular moment.

#### Mandelbug

When the cause of the bug is too complex to understand, and the resulting bug appears chaotic, it is called a Mandelbug. These are named after Benoît Mandelbrot, who is considered the father of fractal geometry (fractals are complex, self-similar structures). A bug in an operating system that depends on scheduling is an example of a Mandelbug.

#### Schroedinbug

Sometimes, you look into the code, and find that it has a bug or a problem that should never have allowed it to work in the first place. When you try out the code, the bug promptly shows up, and the software fails! Though it sounds very uncommon, such bugs do occur and are known as Schroedinbugs. They are named after the scientist Erwin Schrödinger, who proposed that in quantum physics, quantum particles like atoms could exist in two or more quantum states.

By observing the problem in the code, you change the outcome — either the software works or breaks. So these kinds of bugs are known as Schroedinbugs.

#### Fractal Bugs

A bug, after which its resolution is found, reveals additional self-similar bugs elsewhere in the code, after which they are fixed, likewise appear elsewhere still.

Next time time you write a program and if it crashes unexpectedly you can tell your teacher or your friends that you have a heisenbug or a bohrbug in your program, let them figure out what the heck that means. Happy Hacking 🙂

References

[2] The Jargon File http://www.catb.org/jargon/html/index.html

## Recursion In Programming

Recursion and recursive functions are a great concept in programming languages. For a beginner it can turn into one of the worst nightmares but once you get into the spirit of programming then writing recursive programs will be a bliss. Recently some of my friends found it difficult to write a recursive program to print the Fibonacci series upto a limit. This is what inspired me to write a small post on recursive functions. My post will be based on C programming. I am not an expert to write a large post on recursive functions but I would like to share with you some interesting things I know on recursion.

Recursion is nothing but the breaking up of a large problem into smaller problems. It is a divide and conquer policy. Here the smaller programs are defined in terms of the larger program, or we can say that a single function calls itself till a base condition is reached.

A recursion

This picture should serve as an example as to what recursion is (How to make such a picture I will explain in some other post)

All recursive functions consist of two parts

• A base case
• A recursive step

It is the recursive step that is defined in terms of itself and it must move closer to the base case. If there is no base case or the recursive step does not reach the base case the program may run infinitely or till it runs out of memory. Almost all iterative programs can be done as a recursive program. Another classical example of solving a problem with recursion is the tower of Hanoi. Read more about it here http://familycoding.com/2012/04/12/tower-of-hanoi/

Recursive functions can make your program look more shorter and neater. But debugging and understanding a recursive program can be a difficult task. But the trick is to identify the base case and the recursive steps.

Here I will demonstrate the Fibonacci series example with and without recursion. Before you look into the program I suggest reading http://braintenance.blogspot.in/2011/08/fibonacci-numbers-math-meets-mysticism.html to really understand the fun in Fibonacci series.

### The Code below shows Fibonacci series Without recursion

#include<stdio.h>
int main()
{
int a=0,b=1,c,i,n;
printf("Enter the number of elelments of fibonacci series needed\n");
scanf("%d",&n);
printf("\n %d  ",b);// to display the initial 1 of series
for(i=0;i<n-1;i++)
{
c=a+b;
printf("\n %d  ",c);
a=b;
b=c;
}
printf("\n\n");
return 0;
}

### The Code below shows Fibonacci series with recursion

#include<stdio.h>
int main()
{
int n,a=0,b=1;
printf("\n Enter the number of elements of Fibonacci series to be displayed = ");
scanf("%d",&n);
printf("\n %d  ",b);// to display the initial 1 of series
fib(a,b,n-1);
printf("\n********************************************\n");
return 0;
}
int fib(int a,int b,int n)
{
if(n!=0)
{
printf("%d  ",(a+b));
n--;
fib(b,a+b,n);
}
else
{
return 0;
}
}

So much has been said about Recursive functions but any post on recursion would be misleading if I leave out the following points.

• Recursive programs are less efficient as more memory space is used each time a function is called.
• Iterative programs are less time-consuming and easier to write.

Despite that recursion can be fun and can really turn you on if you are a coding maniac.