text:
# PID controller

A proportional–integral–derivative controller (PID controller or three-term controller) is a control loop mechanism employing feedback that is widely used in industrial control systems and a variety of other applications requiring continuously modulated control. A PID controller continuously calculates an error value ${\displaystyle e(t)}$ as the difference between a desired setpoint (SP) and a measured process variable (PV) and applies a correction based on proportional, integral, and derivative terms (denoted P, I, and D respectively), hence the name.

In practical terms, it automatically applies an accurate and responsive correction to a control function. An everyday example is the cruise control on a car, where ascending a hill would lower speed if only constant engine power were applied. The controller's PID algorithm restores the measured speed to the desired speed with minimal delay and overshoot by increasing the power output of the engine in a controlled manner.

The first theoretical analysis and practical application was in the field of automatic steering systems for ships, developed from the early 1920s onwards. It was then used for automatic process control in the manufacturing industry, where it was widely implemented in at first pneumatic, and then electronic controllers. Today the PID concept is used universally in applications requiring accurate and optimized automatic control.

## Fundamental operation

A block diagram of a PID controller in a feedback loop. r(t) is the desired process value or setpoint (SP), and y(t) is the measured process value (PV).

The distinguishing feature of the PID controller is the ability to use the three control terms of proportional, integral and derivative influence on the controller output to apply accurate and optimal control. The block diagram on the right shows the principles of how these terms are generated and applied. It shows a PID controller, which continuously calculates an error value ${\displaystyle e(t)}$ as the difference between a desired setpoint ${\displaystyle {\text{SP}}=r(t)}$ and a measured process variable ${\displaystyle {\text{PV}}=y(t)}$: ${\displaystyle e(t)=r(t)-y(t)}$, and applies a correction based on proportional, integral, and derivative terms. The controller attempts to minimize the error over time by adjustment of a control variable ${\displaystyle u(t)}$, such as the opening of a control valve, to a new value determined by a weighted sum of the control terms.

In this model:

• Term P is proportional to the current value of the SP − PV error ${\displaystyle e(t)}$. For example, if the error is large and positive, the control output will be proportionately large and positive, taking into account the gain factor "K". Using proportional control alone will result in an error between the setpoint and the actual process value because it requires an error to generate the proportional response. If there is no error, there is no corrective response.
• Term I accounts for past values of the SP − PV error and integrates them over time to produce the I term. For example, if there is a residual SP − PV error after the application of proportional control, the integral term seeks to eliminate the residual error by adding a control effect due to the historic cumulative value of the error. When the error is eliminated, the integral term will cease to grow. This will result in the proportional effect diminishing as the error decreases, but this is compensated for by the growing integral effect.
• Term D is a best estimate of the future trend of the SP − PV error, based on its current rate of change. It is sometimes called "anticipatory control", as it is effectively seeking to reduce the effect of the SP − PV error by exerting a control influence generated by the rate of error change. The more rapid the change, the greater the controlling or damping effect.[1]

Tuning – The balance of these effects is achieved by loop tuning to produce the optimal control function. The tuning constants are shown below as "K" and must be derived for each control application, as they depend on the response characteristics of the complete loop external to the controller. These are dependent on the behavior of the measuring sensor, the final control element (such as a control valve), any control signal delays and the process itself. Approximate values of constants can usually be initially entered knowing the type of application, but they are normally refined, or tuned, by "bumping" the process in practice by introducing a setpoint change and observing the system response.

Control action – The mathematical model and practical loop above both use a direct control action for all the terms, which means an increasing positive error results in an increasing positive control output correction. The system is called reverse acting if it is necessary to apply negative corrective action. For instance, if the valve in the flow loop was 100–0% valve opening for 0–100% control output – meaning that the controller action has to be reversed. Some process control schemes and final control elements require this reverse action. An example would be a valve for cooling water, where the fail-safe mode, in the case of loss of signal, would be 100% opening of the valve; therefore 0% controller output needs to cause 100% valve opening.

### Mathematical form

The overall control function ${\displaystyle u(t)=K_{\text{p}}e(t)+K_{\text{i}}\int _{0}^{t}e(\tau )\,\mathrm {d} \tau +K_{\text{d}}{\frac {\mathrm {d} e(t)}{\mathrm {d} t}},}$

where ${\displaystyle K_{\text{p}}}$, ${\displaystyle K_{\text{i}}}$, and ${\displaystyle K_{\text{d}}}$, all non-negative, denote the coefficients for the proportional, integral, and derivative terms respectively (sometimes denoted P, I, and D).

In the standard form of the equation (see later in article), ${\displaystyle K_{\text{i}}}$ and ${\displaystyle K_{\text{d}}}$ are respectively replaced by ${\displaystyle K_{\text{p}}/T_{\text{i}}}$ and ${\displaystyle K_{\text{p}}T_{\text{d}}}$; the advantage of this being that ${\displaystyle T_{\text{i}}}$ and ${\displaystyle T_{\text{d}}}$ have some understandable physical meaning, as they represent the integration time and the derivative time respectively.

${\displaystyle u(t)=K_{\text{p}}\left(e(t)+{\frac {1}{T_{\text{i}}}}\int _{0}^{t}e(\tau )\,\mathrm {d} \tau +T_{\text{d}}{\frac {\mathrm {d} e(t)}{\mathrm {d} t}}\right),}$

### Selective use of control terms

Although a PID controller has three control terms, some applications need only one or two terms to provide appropriate control. This is achieved by setting the unused parameters to zero and is called a PI, PD, P or I controller in the absence of the other control actions. PI controllers are fairly common in applications where derivative action would be sensitive to measurement noise, but the integral term is often needed for the system to reach its target value.

### Applicability

The use of the PID algorithm does not guarantee optimal control of the system or its control stability (see § Limitations, below). Situations may occur where there are excessive delays: the measurement of the process value is delayed, or the control action does not apply quickly enough. In these cases lead–lag compensation is required to be effective. The response of the controller can be described in terms of its responsiveness to an error, the degree to which the system overshoots a setpoint, and the degree of any system oscillation. But the PID controller is broadly applicable since it relies only on the response of the measured process variable, not on knowledge or a model of the underlying process.

## History

Early PID theory was developed by observing the actions of helmsmen in keeping a vessel on course in the face of varying influences such as wind and sea state.
Pneumatic PID (three-term) controller. The magnitudes of the three terms (P, I and D) are adjusted by the dials at the top.

### Origins

Continuous control, before PID controllers were fully understood and implemented, has one of its origins in the centrifugal governor, which uses rotating weights to control a process. This had been invented by Christiaan Huygens in the 17th century to regulate the gap between millstones in windmills depending on the speed of rotation, and thereby compensate for the variable speed of grain feed.[2][3]

With the invention of the low-pressure stationary steam engine there was a need for automatic speed control, and James Watt’s self-designed "conical pendulum" governor, a set of revolving steel balls attached to a vertical spindle by link arms, came to be an industry standard. This was based on the millstone-gap control concept.[4]

Rotating-governor speed control, however, was still variable under conditions of varying load, where the shortcoming of what is now known as proportional control alone was evident. The error between the desired speed and the actual speed would increase with increasing load. In the 19th century, the theoretical basis for the operation of governors was first described by James Clerk Maxwell in 1868 in his now-famous paper On Governors. He explored the mathematical basis for control stability, and progressed a good way towards a solution, but made an appeal for mathematicians to examine the problem.[5][4] The problem was examined further in 1874 by Edward Routh, Charles Sturm, and in 1895, Adolf Hurwitz, all of whom contributed to the establishment of control stability criteria.[4] In subsequent applications, speed governors were further refined, notably by American scientist Willard Gibbs, who in 1872 theoretically analyzed Watt's conical pendulum governor.

About this time, the invention of the Whitehead torpedo posed a control problem that required accurate control of the running depth. Use of a depth pressure sensor alone proved inadequate, and a pendulum that measured the fore and aft pitch of the torpedo was combined with depth measurement to become the pendulum-and-hydrostat control. Pressure control provided only a proportional control that, if the control gain was too high, would become unstable and go into overshoot with considerable instability of depth-holding. The pendulum added what is now known as derivative control, which damped the oscillations by detecting the torpedo dive/climb angle and thereby the rate-of-change of depth.[6] This development (named by Whitehead as "The Secret" to give no clue to its action) was around 1868.[7]

Another early example of a PID-type controller was developed by Elmer Sperry in 1911 for ship steering, though his work was intuitive rather than mathematically-based.[8]

It was not until 1922, however, that a formal control law for what we now call PID or three-term control was first developed using theoretical analysis, by Russian American engineer Nicolas Minorsky.[9] Minorsky was researching and designing automatic ship steering for the US Navy and based his analysis on observations of a helmsman. He noted the helmsman steered the ship based not only on the current course error but also on past error, as well as the current rate of change;[10] this was then given a mathematical treatment by Minorsky.[4] His goal was stability, not general control, which simplified the problem significantly. While proportional control provided stability against small disturbances, it was insufficient for dealing with a steady disturbance, notably a stiff gale (due to steady-state error), which required adding the integral term. Finally, the derivative term was added to improve stability and control.

Trials were carried out on the USS New Mexico, with the controllers controlling the angular velocity (not the angle) of the rudder. PI control yielded sustained yaw (angular error) of ±2°. Adding the D element yielded a yaw error of ±1/6°, better than most helmsmen could achieve.[11]

The Navy ultimately did not adopt the system due to resistance by personnel. Similar work was carried out and published by several others in the 1930s.

### Industrial control

Proportional control using nozzle and flapper high gain amplifier and negative feedback

The wide use of feedback controllers did not become feasible until the development of wideband high-gain amplifiers to use the concept of negative feedback. This had been developed in telephone engineering electronics by Harold Black in the late 1920s, but not published until 1934.[4] Independently, Clesson E Mason of the Foxboro Company in 1930 invented a wide-band pneumatic controller by combining the nozzle and flapper high-gain pneumatic amplifier, which had been invented in 1914, with negative feedback from the controller output. This dramatically increased the linear range of operation of the nozzle and flapper amplifier, and integral control could also be added by the use of a precision bleed valve and a bellows generating the integral term. The result was the "Stabilog" controller which gave both proportional and integral functions using feedback bellows.[4] The integral term was called Reset.[12] Later the derivative term was added by a further bellows and adjustable orifice.

From about 1932 onwards, the use of wideband pneumatic controllers increased rapidly in a variety of control applications. Air pressure was used for generating the controller output, and also for powering process modulating devices such as diaphragm-operated control valves. They were simple low maintenance devices that operated well in harsh industrial environments and did not present explosion risks in hazardous locations. They were the industry standard for many decades until the advent of discrete electronic controllers and distributed control systems.

With these controllers, a pneumatic industry signaling standard of 3–15 psi (0.2–1.0 bar) was established, which had an elevated zero to ensure devices were working within their linear characteristic and represented the control range of 0-100%.

In the 1950s, when high gain electronic amplifiers became cheap and reliable, electronic PID controllers became popular, and the pneumatic standard was emulated by 10-50 mA and 4–20 mA current loop signals (the latter became the industry standard). Pneumatic field actuators are still widely used because of the advantages of pneumatic energy for control valves in process plant environments.

Showing the evolution of analog control loop signaling from the pneumatic to the electronic eras
Current loops used for sensing and control signals. A modern electronic "smart" valve positioner is shown, which will incorporate its own PID controller.

Most modern PID controls in industry are implemented as computer software in distributed control systems (DCS), programmable logic controllers (PLCs), or discrete compact controllers.

### Electronic analog controllers

Electronic analog PID control loops were often found within more complex electronic systems, for example, the head positioning of a disk drive, the power conditioning of a power supply, or even the movement-detection circuit of a modern seismometer. Discrete electronic analog controllers have been largely replaced by digital controllers using microcontrollers or FPGAs to implement PID algorithms. However, discrete analog PID controllers are still used in niche applications requiring high-bandwidth and low-noise performance, such as laser-diode controllers.[13]

## Control loop example

Consider a robotic arm[14] that can be moved and positioned by a control loop. An electric motor may lift or lower the arm, depending on forward or reverse power applied, but power cannot be a simple function of position because of the inertial mass of the arm, forces due to gravity, external forces on the arm such as a load to lift or work to be done on an external object.

• The sensed position is the process variable (PV).
• The desired position is called the setpoint (SP).
• The difference between the PV and SP is the error (e), which quantifies whether the arm is too low or too high and by how much.
• The input to the process (the electric current in the motor) is the output from the PID controller. It is called either the manipulated variable (MV) or the control variable (CV).

By measuring the position (PV), and subtracting it from the setpoint (SP), the error (e) is found, and from it the controller calculates how much electric current to supply to the motor (MV).

### Proportional

The obvious method is proportional control: the motor current is set in proportion to the existing error. However, this method fails if, for instance, the arm has to lift different weights: a greater weight needs a greater force applied for the same error on the down side, but a smaller force if the error is low on the upside. That's where the integral and derivative terms play their part.

### Integral

An integral term increases action in relation not only to the error but also the time for which it has persisted. So, if the applied force is not enough to bring the error to zero, this force will be increased as time passes. A pure "I" controller could bring the error to zero, but it would be both slow reacting at the start (because the action would be small at the beginning, depending on time to get significant) and brutal (the action increases as long as the error is positive, even if the error has started to approach zero).

### Derivative

A derivative term does not consider the error (meaning it cannot bring it to zero: a pure D controller cannot bring the system to its setpoint), but the rate of change of error, trying to bring this rate to zero. It aims at flattening the error trajectory into a horizontal line, damping the force applied, and so reduces overshoot (error on the other side because of too great applied force).

Applying too much integral when the error is small and decreasing will lead to overshoot. After overshooting, if the controller were to apply a large correction in the opposite direction and repeatedly overshoot the desired position, the output would oscillate around the setpoint in either a constant, growing, or decaying sinusoid. If the amplitude of the oscillations increases with time, the system is unstable. If they decrease, the system is stable. If the oscillations remain at a constant magnitude, the system is marginally stable.

### Control damping

In the interest of achieving a controlled arrival at the desired position (SP) in a timely and accurate way, the controlled system needs to be critically damped. A well-tuned position control system will also apply the necessary currents to the controlled motor so that the arm pushes and pulls as necessary to resist external forces trying to move it away from the required position. The setpoint itself may be generated by an external system, such as a PLC or other computer system, so that it continuously varies depending on the work that the robotic arm is expected to do. A well-tuned PID control system will enable the arm to meet these changing requirements to the best of its capabilities.

### Response to disturbances

If a controller starts from a stable state with zero error (PV = SP), then further changes by the controller will be in response to changes in other measured or unmeasured inputs to the process that affect the process, and hence the PV. Variables that affect the process other than the MV are known as disturbances. Generally, controllers are used to reject disturbances and to implement setpoint changes. A change in load on the arm constitutes a disturbance to the robot arm control process.

### Applications

In theory, a controller can be used to control any process that has a measurable output (PV), a known ideal value for that output (SP), and an input to the process (MV) that will affect the relevant PV. Controllers are used in industry to regulate temperature, pressure, force, feed rate,[15] flow rate, chemical composition (component concentrations), weight, position, speed, and practically every other variable for which a measurement exists.

## Controller theory

This section describes the parallel or non-interacting form of the PID controller. For other forms please see the section Alternative nomenclature and forms.

The PID control scheme is named after its three correcting terms, whose sum constitutes the manipulated variable (MV). The proportional, integral, and derivative terms are summed to calculate the output of the PID controller. Defining ${\displaystyle u(t)}$ as the controller output, the final form of the PID algorithm is

${\displaystyle u(t)=\mathrm {MV} (t)=K_{\text{p}}e(t)+K_{\text{i}}\int _{0}^{t}e(\tau )\,d\tau +K_{\text{d}}{\frac {de(t)}{dt}},}$

where

${\displaystyle K_{\text{p}}}$ is the proportional gain, a tuning parameter,
${\displaystyle K_{\text{i}}}$ is the integral gain, a tuning parameter,
${\displaystyle K_{\text{d}}}$ is the derivative gain, a tuning parameter,
${\displaystyle e(t)=\mathrm {SP} -\mathrm {PV} (t)}$ is the error (SP is the setpoint, and PV(t) is the process variable),
${\displaystyle t}$ is the time or instantaneous time (the present),
${\displaystyle \tau }$ is the variable of integration (takes on values from time 0 to the present ${\displaystyle t}$).

Equivalently, the transfer function in the Laplace domain of the PID controller is

${\displaystyle L(s)=K_{\text{p}}+K_{\text{i}}/s+K_{\text{d}}s,}$

where ${\displaystyle s}$ is the complex frequency.

### Proportional term

Response of PV to step change of SP vs time, for three values of Kp (Ki and Kd held constant)

The proportional term produces an output value that is proportional to the current error value. The proportional response can be adjusted by multiplying the error by a constant Kp, called the proportional gain constant.

The proportional term is given by

${\displaystyle P_{\text{out}}=K_{\text{p}}e(t).}$

A high proportional gain results in a large change in the output for a given change in the error. If the proportional gain is too high, the system can become unstable (see the section on loop tuning). In contrast, a small gain results in a small output response to a large input error, and a less responsive or less sensitive controller. If the proportional gain is too low, the control action may be too small when responding to system disturbances. Tuning theory and industrial practice indicate that the proportional term should contribute the bulk of the output change.[citation needed]

The steady-state error is the difference between the desired final output and the actual one.[16] Because a non-zero error is required to drive it, a proportional controller generally operates with a steady-state error.[a] Steady-state error (SSE) is proportional to the process gain and inversely proportional to proportional gain. SSE may be mitigated by adding a compensating bias term to the setpoint AND output or corrected dynamically by adding an integral term.

### Integral term

Response of PV to step change of SP vs time, for three values of Ki (Kp and Kd held constant)

The contribution from the integral term is proportional to both the magnitude of the error and the duration of the error. The integral in a PID controller is the sum of the instantaneous error over time and gives the accumulated offset that should have been corrected previously. The accumulated error is then multiplied by the integral gain (Ki) and added to the controller output.

The integral term is given by

${\displaystyle I_{\text{out}}=K_{\text{i}}\int _{0}^{t}e(\tau )\,d\tau .}$

The integral term accelerates the movement of the process towards setpoint and eliminates the residual steady-state error that occurs with a pure proportional controller. However, since the integral term responds to accumulated errors from the past, it can cause the present value to overshoot the setpoint value (see the section on loop tuning).

### Derivative term

Response of PV to step change of SP vs time, for three values of Kd (Kp and Ki held constant)

The derivative of the process error is calculated by determining the slope of the error over time and multiplying this rate of change by the derivative gain Kd. The magnitude of the contribution of the derivative term to the overall control action is termed the derivative gain, Kd.

The derivative term is given by

${\displaystyle D_{\text{out}}=K_{\text{d}}{\frac {de(t)}{dt}}.}$

Derivative action predicts system behavior and thus improves settling time and stability of the system.[17][18] An ideal derivative is not causal, so that implementations of PID controllers include an additional low-pass filtering for the derivative term to limit the high-frequency gain and noise. Derivative action is seldom used in practice though – by one estimate in only 25% of deployed controllers[citation needed] – because of its variable impact on system stability in real-world applications.

## Loop tuning

Tuning a control loop is the adjustment of its control parameters (proportional band/gain, integral gain/reset, derivative gain/rate) to the optimum values for the desired control response. Stability (no unbounded oscillation) is a basic requirement, but beyond that, different systems have different behavior, different applications have different requirements, and requirements may conflict with one another.

PID tuning is a difficult problem, even though there are only three parameters and in principle is simple to describe, because it must satisfy complex criteria within the limitations of PID control. There are accordingly various methods for loop tuning, and more sophisticated techniques are the subject of patents; this section describes some traditional manual methods for loop tuning.

Designing and tuning a PID controller appears to be conceptually intuitive, but can be hard in practice, if multiple (and often conflicting) objectives such as short transient and high stability are to be achieved. PID controllers often provide acceptable control using default tunings, but performance can generally be improved by careful tuning, and performance may be unacceptable with poor tuning. Usually, initial designs need to be adjusted repeatedly through computer simulations until the closed-loop system performs or compromises as desired.

Some processes have a degree of nonlinearity and so parameters that work well at full-load conditions don't work when the process is starting up from no-load; this can be corrected by gain scheduling (using different parameters in different operating regions).

### Stability

If the PID controller parameters (the gains of the proportional, integral and derivative terms) are chosen incorrectly, the controlled process input can be unstable, i.e., its output diverges, with or without oscillation, and is limited only by saturation or mechanical breakage. Instability is caused by excess gain, particularly in the presence of significant lag.

Generally, stabilization of response is required and the process must not oscillate for any combination of process conditions and setpoints, though sometimes marginal stability (bounded oscillation) is acceptable or desired.[citation needed]

Mathematically, the origins of instability can be seen in the Laplace domain.[19]

The total loop transfer function is:

${\displaystyle H(s)={\frac {K(s)G(s)}{1+K(s)G(s)}}}$

where

${\displaystyle K(s)}$ is the PID transfer function and
${\displaystyle G(s)}$ is the plant transfer function

The system is called unstable where the closed loop transfer function diverges for some ${\displaystyle s}$.[19] This happens for situations where ${\displaystyle K(s)G(s)=-1}$. Typically, this happens when ${\displaystyle |K(s)G(s)|=1}$ with a 180 degree phase shift. Stability is guaranteed when ${\displaystyle K(s)G(s)<1}$ for frequencies that suffer high phase shifts. A more general formalism of this effect is known as the Nyquist stability criterion.

### Optimal behavior

The optimal behavior on a process change or setpoint change varies depending on the application.

Two basic requirements are regulation (disturbance rejection – staying at a given setpoint) and command tracking (implementing setpoint changes) – these refer to how well the controlled variable tracks the desired value. Specific criteria for command tracking include rise time and settling time. Some processes must not allow an overshoot of the process variable beyond the setpoint if, for example, this would be unsafe. Other processes must minimize the energy expended in reaching a new setpoint.

### Overview of tuning methods

There are several methods for tuning a PID loop. The most effective methods generally involve the development of some form of process model, then choosing P, I, and D based on the dynamic model parameters. Manual tuning methods can be relatively time-consuming, particularly for systems with long loop times.

The choice of method will depend largely on whether or not the loop can be taken offline for tuning, and on the response time of the system. If the system can be taken offline, the best tuning method often involves subjecting the system to a step change in input, measuring the output as a function of time, and using this response to determine the control parameters.[citation needed]

Choosing a tuning method
Manual tuning No mathematics required; online. Requires experienced personnel.[citation needed]
Ziegler–Nichols [b] Proven method; online. Process upset, some trial-and-error, very aggressive tuning.[citation needed]
Tyreus Luyben Proven method; online. Process upset, some trial-and-error, very aggressive tuning.[citation needed]
Software tools Consistent tuning; online or offline - can employ computer-automated control system design (CAutoD) techniques; may include valve and sensor analysis; allows simulation before downloading; can support non-steady-state (NSS) tuning. Some cost or training involved.[21]
Cohen–Coon Good process models. Some mathematics; offline; only good for first-order processes.[citation needed]
Åström-Hägglund Can be used for auto tuning; amplitude is minimum so this method has lowest process upset The process itself is inherently oscillatory.[citation needed]

### Manual tuning

If the system must remain online, one tuning method is to first set ${\displaystyle K_{i}}$ and ${\displaystyle K_{d}}$ values to zero. Increase the ${\displaystyle K_{p}}$ until the output of the loop oscillates, then the ${\displaystyle K_{p}}$ should be set to approximately half of that value for a "quarter amplitude decay" type response. Then increase ${\displaystyle K_{i}}$ until any offset is corrected in sufficient time for the process. However, too much ${\displaystyle K_{i}}$ will cause instability. Finally, increase ${\displaystyle K_{d}}$, if required, until the loop is acceptably quick to reach its reference after a load disturbance. However, too much ${\displaystyle K_{d}}$ will cause excessive response and overshoot. A fast PID loop tuning usually overshoots slightly to reach the setpoint more quickly; however, some systems cannot accept overshoot, in which case an overdamped closed-loop system is required, which will require a ${\displaystyle K_{p}}$ setting significantly less than half that of the ${\displaystyle K_{p}}$ setting that was causing oscillation.[citation needed]

Effects of varying PID parameters (Kp,Ki,Kd) on the step response of a system
Effects of increasing a parameter independently[22][23]
Parameter Rise time Overshoot Settling time Steady-state error Stability
${\displaystyle K_{p}}$ Decrease Increase Small change Decrease Degrade
${\displaystyle K_{i}}$ Decrease Increase Increase Eliminate Degrade
${\displaystyle K_{d}}$ Minor change Decrease Decrease No effect in theory Improve if ${\displaystyle K_{d}}$ small

### Ziegler–Nichols method

Another heuristic tuning method is known as the Ziegler–Nichols method, introduced by John G. Ziegler and Nathaniel B. Nichols in the 1940s. As in the method above, the ${\displaystyle K_{i}}$ and ${\displaystyle K_{d}}$ gains are first set to zero. The proportional gain is increased until it reaches the ultimate gain, ${\displaystyle K_{u}}$, at which the output of the loop starts to oscillate constantly. ${\displaystyle K_{u}}$ and the oscillation period ${\displaystyle T_{u}}$ are used to set the gains as follows:

Ziegler–Nichols method
Control Type ${\displaystyle K_{p}}$ ${\displaystyle K_{i}}$ ${\displaystyle K_{d}}$
P ${\displaystyle 0.50{K_{u}}}$
PI ${\displaystyle 0.45{K_{u}}}$ ${\displaystyle 0.54{K_{u}}/T_{u}}$
PID ${\displaystyle 0.60{K_{u}}}$ ${\displaystyle 1.2{K_{u}}/T_{u}}$ ${\displaystyle 3{K_{u}}{T_{u}}/40}$

These gains apply to the ideal, parallel form of the PID controller. When applied to the standard PID form, only the integral and derivative gains ${\displaystyle K_{i}}$ and ${\displaystyle K_{d}}$ are dependent on the oscillation period ${\displaystyle T_{u}}$.

### Cohen–Coon parameters

This method was developed in 1953 and is based on a first-order + time delay model. Similar to the Ziegler–Nichols method, a set of tuning parameters were developed to yield a closed-loop response with a decay ratio of 1/4. Arguably the biggest problem with these parameters is that a small change in the process parameters could potentially cause a closed-loop system to become unstable.

### Relay (Åström–Hägglund) method

Published in 1984 by Karl Johan Åström and Tore Hägglund,[24] the relay method temporarily operates the process using bang-bang control and measures the resultant oscillations. The output is switched (as if by a relay, hence the name) between two values of the control variable. The values must be chosen so the process will cross the setpoint, but need not be 0% and 100%; by choosing suitable values, dangerous oscillations can be avoided.

As long as the process variable is below the setpoint, the control output is set to the higher value. As soon as it rises above the setpoint, the control output is set to the lower value. Ideally, the output waveform is nearly square, spending equal time above and below the setpoint. The period and amplitude of the resultant oscillations are measured, and used to compute the ultimate gain and period, which are then fed into the Ziegler–Nichols method.

Specifically, the ultimate period ${\displaystyle T_{u}}$ is assumed to be equal to the observed period, and the ultimate gain is computed as ${\displaystyle K_{u}=4b/\pi a,}$ where a is the amplitude of the process variable oscillation, and b is the amplitude of the control output change which caused it.

There are numerous variants on the relay method.[25]

### First order with dead time model

The transfer function for a first-order process, with dead time, is:

${\displaystyle y(s)={\frac {k_{p}e^{-\theta s}}{\tau _{p}s+1}}*u(s)}$

where kp is the process gain, τp is the time constant, θ is the dead time, and u(s) is a step change input. Converting this transfer function to the time domain results in:

${\displaystyle y(t)=k_{p}\Delta u(1-e^{\frac {-t-\theta }{\tau _{p}}})}$

using the same parameters found above.

It is important when using this method to apply a large enough step change input that the output can be measured; however, too large of a step change can affect the process stability. Additionally, a larger step change will ensure that the output is not changing due to a disturbance (for best results, try to minimize disturbances when performing the step test).

One way to determine the parameters for the first-order process is using the 63.2% method. In this method, the process gain (kp) is equal to the change in output divided by the change in input. The dead time (θ) is the amount of time between when the step change occurred and when the output first changed. The time constant (τp) is the amount of time it takes for the output to reach 63.2% of the new steady-state value after the step change. One downside to using this method is that the time to reach a new steady-state value can take a while if the process has large time constants.[26]

### Tuning software

Most modern industrial facilities no longer tune loops using the manual calculation methods shown above. Instead, PID tuning and loop optimization software are used to ensure consistent results. These software packages will gather the data, develop process models, and suggest optimal tuning. Some software packages can even develop tuning by gathering data from reference changes.

Mathematical PID loop tuning induces an impulse in the system and then uses the controlled system's frequency response to design the PID loop values. In loops with response times of several minutes, mathematical loop tuning is recommended, because trial and error can take days just to find a stable set of loop values. Optimal values are harder to find. Some digital loop controllers offer a self-tuning feature in which very small setpoint changes are sent to the process, allowing the controller itself to calculate optimal tuning values.

Another approach calculates initial values via the Ziegler–Nichols method, and uses a numerical optimization technique to find better PID coefficients.[27]

Other formulas are available to tune the loop according to different performance criteria. Many patented formulas are now embedded within PID tuning software and hardware modules.[28]

Advances in automated PID loop tuning software also deliver algorithms for tuning PID Loops in a dynamic or non-steady state (NSS) scenario. The software will model the dynamics of a process, through a disturbance, and calculate PID control parameters in response.[29]

## Limitations

While PID controllers are applicable to many control problems, and often perform satisfactorily without any improvements or only coarse tuning, they can perform poorly in some applications and do not in general provide optimal control. The fundamental difficulty with PID control is that it is a feedback control system, with constant parameters, and no direct knowledge of the process, and thus overall performance is reactive and a compromise. While PID control is the best controller in an observer without a model of the process, better performance can be obtained by overtly modeling the actor of the process without resorting to an observer.

PID controllers, when used alone, can give poor performance when the PID loop gains must be reduced so that the control system does not overshoot, oscillate or hunt about the control setpoint value. They also have difficulties in the presence of non-linearities, may trade-off regulation versus response time, do not react to changing process behavior (say, the process changes after it has warmed up), and have lag in responding to large disturbances.

The most significant improvement is to incorporate feed-forward control with knowledge about the system, and using the PID only to control error. Alternatively, PIDs can be modified in more minor ways, such as by changing the parameters (either gain scheduling in different use cases or adaptively modifying them based on performance), improving measurement (higher sampling rate, precision, and accuracy, and low-pass filtering if necessary), or cascading multiple PID controllers.

### Linearity and symmetry

PID controllers work best when the loop to be controlled is linear and symmetric. Thus, their performance in non-linear and asymmetric systems is degraded.

A non-linear valve, for instance, in a flow control application, will result in variable loop sensitivity, requiring dampened action to prevent instability. One solution is the use of the valve's non-linear characteristic in the control algorithm to compensate for this.

An asymmetric application, for example, is temperature control in HVAC systems using only active heating (via a heating element), where there is only passive cooling available. When it is desired to lower the controlled temperature the heating output is off, but there is no active cooling due to control output. Any overshoot of rising temperature can therefore only be corrected slowly; it cannot be forced downward by the control output. In this case the PID controller could be tuned to be over-damped, to prevent or reduce overshoot, but this reduces performance by increasing the settling time of a rising temperature to the set point. The inherent degradation of control quality in this application could be solved by application of active cooling.

### Noise in derivative term

A problem with the derivative term is that it amplifies higher frequency measurement or process noise that can cause large amounts of change in the output. It is often helpful to filter the measurements with a low-pass filter in order to remove higher-frequency noise components. As low-pass filtering and derivative control can cancel each other out, the amount of filtering is limited. Therefore, low noise instrumentation can be important. A nonlinear median filter may be used, which improves the filtering efficiency and practical performance.[30] In some cases, the differential band can be turned off with little loss of control. This is equivalent to using the PID controller as a PI controller.

## Modifications to the algorithm

The basic PID algorithm presents some challenges in control applications that have been addressed by minor modifications to the PID form.

### Integral windup

One common problem resulting from the ideal PID implementations is integral windup. Following a large change in setpoint the integral term can accumulate an error larger than the maximal value for the regulation variable (windup), thus the system overshoots and continues to increase until this accumulated error is unwound. This problem can be addressed by:

• Disabling the integration until the PV has entered the controllable region
• Preventing the integral term from accumulating above or below pre-determined bounds
• Back-calculating the integral term to constrain the regulator output within feasible bounds.[31]

### Overshooting from known disturbances

For example, a PID loop is used to control the temperature of an electric resistance furnace where the system has stabilized. Now when the door is opened and something cold is put into the furnace the temperature drops below the setpoint. The integral function of the controller tends to compensate for error by introducing another error in the positive direction. This overshoot can be avoided by freezing of the integral function after the opening of the door for the time the control loop typically needs to reheat the furnace.

### PI controller

Basic block of a PI controller

A PI controller (proportional-integral controller) is a special case of the PID controller in which the derivative (D) of the error is not used.

The controller output is given by

${\displaystyle K_{P}\Delta +K_{I}\int \Delta \,dt}$

where ${\displaystyle \Delta }$ is the error or deviation of actual measured value (PV) from the setpoint (SP).

${\displaystyle \Delta =SP-PV.}$

A PI controller can be modelled easily in software such as Simulink or Xcos using a "flow chart" box involving Laplace operators:

${\displaystyle C={\frac {G(1+\tau s)}{\tau s}}}$

where

${\displaystyle G=K_{P}}$ = proportional gain
${\displaystyle {\frac {G}{\tau }}=K_{I}}$ = integral gain

Setting a value for ${\displaystyle G}$ is often a trade off between decreasing overshoot and increasing settling time.

The lack of derivative action may make the system more steady in the steady state in the case of noisy data. This is because derivative action is more sensitive to higher-frequency terms in the inputs.

Without derivative action, a PI-controlled system is less responsive to real (non-noise) and relatively fast alterations in state and so the system will be slower to reach setpoint and slower to respond to perturbations than a well-tuned PID system may be.

Many PID loops control a mechanical device (for example, a valve). Mechanical maintenance can be a major cost and wear leads to control degradation in the form of either stiction or backlash in the mechanical response to an input signal. The rate of mechanical wear is mainly a function of how often a device is activated to make a change. Where wear is a significant concern, the PID loop may have an output deadband to reduce the frequency of activation of the output (valve). This is accomplished by modifying the controller to hold its output steady if the change would be small (within the defined deadband range). The calculated output must leave the deadband before the actual output will change.

### Setpoint step change

The proportional and derivative terms can produce excessive movement in the output when a system is subjected to an instantaneous step increase in the error, such as a large setpoint change. In the case of the derivative term, this is due to taking the derivative of the error, which is very large in the case of an instantaneous step change. As a result, some PID algorithms incorporate some of the following modifications:

Setpoint ramping
In this modification, the setpoint is gradually moved from its old value to a newly specified value using a linear or first-order differential ramp function. This avoids the discontinuity present in a simple step change.
Derivative of the process variable
In this case the PID controller measures the derivative of the measured process variable (PV), rather than the derivative of the error. This quantity is always continuous (i.e., never has a step change as a result of changed setpoint). This modification is a simple case of setpoint weighting.
Setpoint weighting
Setpoint weighting adds adjustable factors (usually between 0 and 1) to the setpoint in the error in the proportional and derivative element of the controller. The error in the integral term must be the true control error to avoid steady-state control errors. These two extra parameters do not affect the response to load disturbances and measurement noise and can be tuned to improve the controller's setpoint response.

### Feed-forward

The control system performance can be improved by combining the feedback (or closed-loop) control of a PID controller with feed-forward (or open-loop) control. Knowledge about the system (such as the desired acceleration and inertia) can be fed forward and combined with the PID output to improve the overall system performance. The feed-forward value alone can often provide the major portion of the controller output. The PID controller primarily has to compensate for whatever difference or error remains between the setpoint (SP) and the system response to the open-loop control. Since the feed-forward output is not affected by the process feedback, it can never cause the control system to oscillate, thus improving the system response without affecting stability. Feed forward can be based on the setpoint and on extra measured disturbances. Setpoint weighting is a simple form of feed forward.

For example, in most motion control systems, in order to accelerate a mechanical load under control, more force is required from the actuator. If a velocity loop PID controller is being used to control the speed of the load and command the force being applied by the actuator, then it is beneficial to take the desired instantaneous acceleration, scale that value appropriately and add it to the output of the PID velocity loop controller. This means that whenever the load is being accelerated or decelerated, a proportional amount of force is commanded from the actuator regardless of the feedback value. The PID loop in this situation uses the feedback information to change the combined output to reduce the remaining difference between the process setpoint and the feedback value. Working together, the combined open-loop feed-forward controller and closed-loop PID controller can provide a more responsive control system.

### Bumpless operation

PID controllers are often implemented with a "bumpless" initialization feature that recalculates the integral accumulator term to maintain a consistent process output through parameter changes.[32] A partial implementation is to store the integral gain times the error rather than storing the error and postmultiplying by the integral gain, which prevents discontinuous output when the I gain is changed, but not the P or D gains.

### Other improvements

In addition to feed-forward, PID controllers are often enhanced through methods such as PID gain scheduling (changing parameters in different operating conditions), fuzzy logic, or computational verb logic.[33][34] Further practical application issues can arise from instrumentation connected to the controller. A high enough sampling rate, measurement precision, and measurement accuracy are required to achieve adequate control performance. Another new method for improvement of PID controller is to increase the degree of freedom by using fractional order. The order of the integrator and differentiator add increased flexibility to the controller.[35]

One distinctive advantage of PID controllers is that two PID controllers can be used together to yield better dynamic performance. This is called cascaded PID control. Two controllers are in cascade when they are arranged so that one regulates the set point of the other. A PID controller acts as outer loop controller, which controls the primary physical parameter, such as fluid level or velocity. The other controller acts as inner loop controller, which reads the output of outer loop controller as setpoint, usually controlling a more rapid changing parameter, flowrate or acceleration. It can be mathematically proven[citation needed] that the working frequency of the controller is increased and the time constant of the object is reduced by using cascaded PID controllers.[vague].

For example, a temperature-controlled circulating bath has two PID controllers in cascade, each with its own thermocouple temperature sensor. The outer controller controls the temperature of the water using a thermocouple located far from the heater, where it accurately reads the temperature of the bulk of the water. The error term of this PID controller is the difference between the desired bath temperature and measured temperature. Instead of controlling the heater directly, the outer PID controller sets a heater temperature goal for the inner PID controller. The inner PID controller controls the temperature of the heater using a thermocouple attached to the heater. The inner controller's error term is the difference between this heater temperature setpoint and the measured temperature of the heater. Its output controls the actual heater to stay near this setpoint.

The proportional, integral, and differential terms of the two controllers will be very different. The outer PID controller has a long time constant – all the water in the tank needs to heat up or cool down. The inner loop responds much more quickly. Each controller can be tuned to match the physics of the system it controls – heat transfer and thermal mass of the whole tank or of just the heater – giving better total response.[36][37]

## Alternative nomenclature and forms

### Standard versus parallel (ideal) form

The form of the PID controller most often encountered in industry, and the one most relevant to tuning algorithms is the standard form. In this form the ${\displaystyle K_{p}}$ gain is applied to the ${\displaystyle I_{\mathrm {out} }}$, and ${\displaystyle D_{\mathrm {out} }}$ terms, yielding:

${\displaystyle u(t)=K_{p}\left(e(t)+{\frac {1}{T_{i}}}\int _{0}^{t}e(\tau )\,d\tau +T_{d}{\frac {d}{dt}}e(t)\right)}$

where

${\displaystyle T_{i}}$ is the integral time
${\displaystyle T_{d}}$ is the derivative time

In this standard form, the parameters have a clear physical meaning. In particular, the inner summation produces a new single error value which is compensated for future and past errors. The proportional error term is the current error. The derivative components term attempts to predict the error value at ${\displaystyle T_{d}}$ seconds (or samples) in the future, assuming that the loop control remains unchanged. The integral component adjusts the error value to compensate for the sum of all past errors, with the intention of completely eliminating them in ${\displaystyle T_{i}}$ seconds (or samples). The resulting compensated single error value is then scaled by the single gain ${\displaystyle K_{p}}$ to compute the control variable.

In the parallel form, shown in the controller theory section

${\displaystyle u(t)=K_{p}e(t)+K_{i}\int _{0}^{t}e(\tau )\,d\tau +K_{d}{\frac {d}{dt}}e(t)}$

the gain parameters are related to the parameters of the standard form through ${\displaystyle K_{i}=K_{p}/T_{i}}$ and ${\displaystyle K_{d}=K_{p}T_{d}}$. This parallel form, where the parameters are treated as simple gains, is the most general and flexible form. However, it is also the form where the parameters have the weakest relationship to physical behaviors and is generally reserved for theoretical treatment of the PID controller. The standard form, despite being slightly more complex mathematically, is more common in industry.

### Reciprocal gain, a.k.a. proportional band

In many cases, the manipulated variable output by the PID controller is a dimensionless fraction between 0 and 100% of some maximum possible value, and the translation into real units (such as pumping rate or watts of heater power) is outside the PID controller. The process variable, however, is in dimensioned units such as temperature. It is common in this case to express the gain ${\displaystyle K_{p}}$ not as "output per degree", but rather in the reciprocal form of a proportional band ${\displaystyle 100/K_{p}}$, which is "degrees per full output": the range over which the output changes from 0 to 1 (0% to 100%). Beyond this range, the output is saturated, full-off or full-on. The narrower this band, the higher the proportional gain.

### Basing derivative action on PV

In most commercial control systems, derivative action is based on process variable rather than error. That is, a change in the setpoint does not affect the derivative action. This is because the digitized version of the algorithm produces a large unwanted spike when the setpoint is changed. If the setpoint is constant then changes in the PV will be the same as changes in error. Therefore, this modification makes no difference to the way the controller responds to process disturbances.

### Basing proportional action on PV

Most commercial control systems offer the option of also basing the proportional action solely on the process variable. This means that only the integral action responds to changes in the setpoint. The modification to the algorithm does not affect the way the controller responds to process disturbances. Basing proportional action on PV eliminates the instant and possibly very large change in output caused by a sudden change to the setpoint. Depending on the process and tuning this may be beneficial to the response to a setpoint step.

${\displaystyle \mathrm {MV(t)} =K_{p}\left(\,{-PV(t)}+{\frac {1}{T_{i}}}\int _{0}^{t}{e(\tau )}\,{d\tau }-T_{d}{\frac {d}{dt}}PV(t)\right)}$

King[38] describes an effective chart-based method.

### Laplace form

Sometimes it is useful to write the PID regulator in Laplace transform form:

${\displaystyle G(s)=K_{p}+{\frac {K_{i}}{s}}+K_{d}{s}={\frac {K_{d}{s^{2}}+K_{p}{s}+K_{i}}{s}}}$

Having the PID controller written in Laplace form and having the transfer function of the controlled system makes it easy to determine the closed-loop transfer function of the system.

### Series/interacting form

Another representation of the PID controller is the series, or interacting form

${\displaystyle G(s)=K_{c}({\frac {1}{\tau _{i}{s}}}+1)(\tau _{d}{s}+1)}$

where the parameters are related to the parameters of the standard form through

${\displaystyle K_{p}=K_{c}\cdot \alpha }$, ${\displaystyle T_{i}=\tau _{i}\cdot \alpha }$, and
${\displaystyle T_{d}={\frac {\tau _{d}}{\alpha }}}$

with

${\displaystyle \alpha =1+{\frac {\tau _{d}}{\tau _{i}}}}$.

This form essentially consists of a PD and PI controller in series. As the integral is required to calculate the controller's bias this form provides the ability to track an external bias value which is required to be used for proper implementation of multi-controller advanced control schemes.

### Discrete implementation

The analysis for designing a digital implementation of a PID controller in a microcontroller (MCU) or FPGA device requires the standard form of the PID controller to be discretized.[39] Approximations for first-order derivatives are made by backward finite differences. The integral term is discretized, with a sampling time ${\displaystyle \Delta t}$, as follows,

${\displaystyle \int _{0}^{t_{k}}e(\tau )\,d\tau =\sum _{i=1}^{k}e(t_{i})\,\Delta t}$

The derivative term is approximated as,

${\displaystyle {\dfrac {de(t_{k})}{dt}}={\dfrac {e(t_{k})-e(t_{k-1})}{\Delta t}}}$

Thus, a velocity algorithm for implementation of the discretized PID controller in a MCU is obtained by differentiating ${\displaystyle u(t)}$, using the numerical definitions of the first and second derivative and solving for ${\displaystyle u(t_{k})}$ and finally obtaining:

${\displaystyle u(t_{k})=u(t_{k-1})+K_{p}\left[\left(1+{\dfrac {\Delta t}{T_{i}}}+{\dfrac {T_{d}}{\Delta t}}\right)e(t_{k})+\left(-1-{\dfrac {2T_{d}}{\Delta t}}\right)e(t_{k-1})+{\dfrac {T_{d}}{\Delta t}}e(t_{k-2})\right]}$

s.t. ${\displaystyle T_{i}=K_{p}/K_{i},T_{d}=K_{d}/K_{p}}$

## Pseudocode

Here is a simple software loop that implements a PID algorithm:[40]

• Kp - proportional gain
• Ki - integral gain
• Kd - derivative gain
• dt - loop interval time
previous_error := 0
integral := 0

loop:
error := setpoint − measured_value
proportional := error;
integral := integral + error × dt
derivative := (error − previous_error) / dt
output := Kp × proportional + Ki × integral + Kd × derivative
previous_error := error
wait(dt)
goto loop

In this example, two variables that will be maintained within the loop are initialized to zero, then the loop begins. The current error is calculated by subtracting the measured_value (the process variable, or PV) from the current setpoint (SP). Then, integral and derivative values are calculated, and these and the error are combined with three preset gain terms – the proportional gain, the integral gain and the derivative gain – to derive an output value.

In the real world, this is D-to-A converted and passed into the process under control as the manipulated variable (MV). The current error is stored elsewhere for re-use in the next differentiation, the program then waits until dt seconds have passed since start, and the loop begins again, reading in new values for the PV and the setpoint and calculating a new value for the error.[40]

Note that for real code, the use of "wait(dt)" might be inappropriate because it doesn't account for time taken by the algorithm itself during the loop, or more importantly, any preemption delaying the algorithm.

## Notes

1. ^ The only exception is where the target value is the same as the value obtained when the controller output is zero.
2. ^ A common assumption often made for Proportional-Integral-Derivative (PID) control design, as done by Ziegler and Nichols, is to take the integral time constant to be four times the derivative time constant. Although this choice is reasonable, selecting the integral time constant to have this value may have had something to do with the fact that, for the ideal case with a derivative term with no filter, the PID transfer function consists of two real and equal zeros in the numerator.[20]

## References

1. ^ Araki, M. "PID Control" (PDF).
2. ^ Hills, Richard L (1996), Power From the Wind, Cambridge University Press
3. ^ Richard E. Bellman (December 8, 2015). Adaptive Control Processes: A Guided Tour. Princeton University Press. ISBN 9781400874668.
4. Bennett, Stuart (1996). "A brief history of automatic control" (PDF). IEEE Control Systems Magazine. 16 (3): 17–25. doi:10.1109/37.506394. Archived from the original (PDF) on 2016-08-09. Retrieved 2014-08-21.
5. ^ Maxwell, J. C. (1868). "On Governors" (PDF). Proceedings of the Royal Society. 100.
6. ^ Newpower, Anthony (2006). Iron Men and Tin Fish: The Race to Build a Better Torpedo during World War II. Praeger Security International. ISBN 978-0-275-99032-9. p.  citing Gray, Edwyn (1991), The Devil's Device: Robert Whitehead and the History of the Torpedo, Annapolis, MD: U.S. Naval Institute, p. 33.
7. ^ Sleeman, C. W. (1880), Torpedoes and Torpedo Warfare, Portsmouth: Griffin & Co., pp. 137–138, which constitutes what is termed as the secret of the fish torpedo.
8. ^ "A Brief Building Automation History". Archived from the original on 2011-07-08. Retrieved 2011-04-04.
9. ^ Minorsky, Nicolas (1922). "Directional stability of automatically steered bodies". J. Amer. Soc. Naval Eng. 34 (2): 280–309. doi:10.1111/j.1559-3584.1922.tb04958.x.
10. ^ Bennett 1993, p. 67
11. ^ Bennett, Stuart (June 1986). A history of control engineering, 1800-1930. IET. pp. 142–148. ISBN 978-0-86341-047-5.
12. ^ Shinskey, F Greg (2004), The power of external-reset feedback (PDF), Control Global
13. ^ Neuhaus, Rudolf. "Diode Laser Locking and Linewidth Narrowing" (PDF). Retrieved June 8, 2015.
14. ^ "Position control system" (PDF). Hacettepe University Department of Electrical and Electronics Engineering.
15. ^ Kebriaei, Reza; Frischkorn, Jan; Reese, Stefanie; Husmann, Tobias; Meier, Horst; Moll, Heiko; Theisen, Werner (2013). "Numerical modelling of powder metallurgical coatings on ring-shaped parts integrated with ring rolling". Material Processing Technology. 213 (1): 2015–2032. doi:10.1016/j.jmatprotec.2013.05.023.
16. ^ Lipták, Béla G. (2003). Instrument Engineers' Handbook: Process control and optimization (4th ed.). CRC Press. p. 108. ISBN 0-8493-1081-4.
17. ^ "Introduction: PID Controller Design". University of Michigan.
18. ^ Tim Wescott (October 2000). "PID without a PhD" (PDF). EE Times-India. Cite journal requires |journal= (help)
19. ^ a b Bechhoefer, John (2005). "Feedback for Physicists: A Tutorial Essay On Control". Reviews of Modern Physics. 77 (3): 783–835. Bibcode:2005RvMP...77..783B. CiteSeerX 10.1.1.124.7043. doi:10.1103/revmodphys.77.783.
20. ^ Atherton, Drek P (December 2014). "Almost Six Decades in Control Engineering". IEEE Control Systems Magazine. 34 (6): 103–110. doi:10.1109/MCS.2014.2359588. S2CID 20233207.
21. ^ Li, Y., et al. (2004) CAutoCSD - Evolutionary search and optimisation enabled computer automated control system design, Int J Automation and Computing, vol. 1, No. 1, pp. 76-88. ISSN 1751-8520.
22. ^ Kiam Heong Ang; Chong, G.; Yun Li (2005). "PID control system analysis, design, and technology" (PDF). IEEE Transactions on Control Systems Technology. 13 (4): 559–576. doi:10.1109/TCST.2005.847331. S2CID 921620.
23. ^ Jinghua Zhong (Spring 2006). "PID Controller Tuning: A Short Tutorial" (PDF). Archived from the original (PDF) on 2015-04-21. Retrieved 2011-04-04. Cite journal requires |journal= (help)
24. ^ Åström, K.J.; Hägglund, T. (July 1984). "Automatic Tuning of Simple Regulators". IFAC Proceedings Volumes. 17 (2): 1867–1872. doi:10.1016/S1474-6670(17)61248-5.
25. ^ Hornsey, Stephen (29 October 2012). "A Review of Relay Auto-tuning Methods for the Tuning of PID-type Controllers". Reinvention. 5 (2).
26. ^ Bequette, B. Wayne (2003). Process Control: Modeling, Design, and Simulation. Upper Saddle River, New Jersey: Prentice Hall. p. 129. ISBN 978-0-13-353640-9.
27. ^ Heinänen, Eero (October 2018). A Method for automatic tuning of PID controller following Luus-Jaakola optimization (PDF) (Master's Thesis ed.). Tampere, Finland: Tampere University of Technology. Retrieved Feb 1, 2019.
28. ^ Li, Yun; Ang, Kiam Heong; Chong, Gregory C.Y. (February 2006). "Patents, software, and hardware for PID control: An overview and analysis of the current art" (PDF). IEEE Control Systems Magazine. 26 (1): 42–54. doi:10.1109/MCS.2006.1580153. S2CID 18461921.
29. ^ Soltesz, Kristian (January 2012). On Automation of the PID Tuning Procedure (PDF) (Licentiate theis). Lund university. 847ca38e-93e8-4188-b3d5-8ec6c23f2132.
30. ^ Li, Y. and Ang, K.H. and Chong, G.C.Y. (2006) PID control system analysis and design - Problems, remedies, and future directions. IEEE Control Systems Magazine, 26 (1). pp. 32-41. ISSN 0272-1708
31. ^ Cooper, Douglas. "Integral (Reset) Windup, Jacketing Logic and the Velocity PI Form". Retrieved 2014-02-18.
32. ^ Cooper, Douglas. "PI Control of the Heat Exchanger". Practical Process Control by Control Guru. Retrieved 2014-02-27.
33. ^ Yang, T. (June 2005). "Architectures of Computational Verb Controllers: Towards a New Paradigm of Intelligent Control". International Journal of Computational Cognition. 3 (2): 74–101. CiteSeerX 10.1.1.152.9564.
34. ^ Liang, Yilong; Yang, Tao (2009). "Controlling fuel annealer using computational verb PID controllers". Proceedings of the 3rd International Conference on Anti-Counterfeiting, Security, and Identification in Communication: 417–420.
35. ^ Tenreiro Machado JA, et al. (2009). "Some Applications of Fractional Calculus in Engineering". Mathematical Problems in Engineering. 2010: 1–34. doi:10.1155/2010/639801. hdl:10400.22/4306.
36. ^ [1] Fundamentals of cascade control | Sometimes two controllers can do a better job of keeping one process variable where you want it. | By Vance VanDoren, PHD, PE | AUGUST 17, 2014
37. ^ [2] | The Benefits of Cascade Control | September 22, 2020 | Watlow
38. ^ King, Myke (2011). Process Control: A Practical Approach. Wiley. pp. 52–78. ISBN 978-0-470-97587-9.
39. ^ "Discrete PI and PID Controller Design and Analysis for Digital Implementation". Scribd.com. Retrieved 2011-04-04.
40. ^ a b "PID process control, a "Cruise Control" example". CodeProject. 2009. Retrieved 4 November 2012.
• Bequette, B. Wayne (2006). Process Control: Modeling, Design, and Simulation. Prentice Hall PTR. ISBN 9789861544779.


text:
# Select certain term containing some patterns and confusing pattern Alternatives in FreeQ

I am considering a function termsContain[func_,list_] which select in an expression func the terms containing the ones in the list. The func in general is a sum of some terms and could also be only one term, for example,

in[1]:= termsContain[a + b + c + a x +b y, {x,y}]
out[1]= a x+b y

in[2]:= termsContain[a + b + c + f[a x +c]+b y, {a x}]
out[2]=f[c + a x]

in[3]:= termsContain[a x , {a x}]
out[3]= a x

in[4]:=  termsContain[a + b + c + a x[i] y[j] +b x[l] y[m] , {x[_]y[_]}]
out[4]= a x[i] y[j]+b x[l] y[m]

I came up with this :

termsContain[func_, list_] :=  func /. (Longest[u___?(Not[FreeQ[#, Alternatives @@ list]] &)] + v___) :> (Plus[u]);

This works fine for the first three examples, but not for the last one. For the last one, this gives only zero

out[4]=0

Try another example which is also not as expected:

in[5]:=termsContain[a + b + c + a x[i] y[j] +b x[l] y[m] +c f[x[l] y[m]], {x[_]y[_]}]
out[5]= c f[x[l] y[m]]

I thought it should give a x[i] y[j] +b x[l] y[m] +c f[x[l] y[m]]. How to understand these results? I did some experiments, the problem seems to be the FreeQ combined with Alternatives. The Alternatives seems not to take one argument, that is, Alternatives[x[_] y[_]] does not match x[_] y[_] as I thought. See these examples,

in[6]:=FreeQ[a x[i] y[j] +b x[l] y[m], x[_] y[_]]
out[6]= False
in[7]:=FreeQ[a x[i] y[j] +b x[l] y[m], Alternatives[x[_] y[_]]]
out[7]= True

But the out[2] and the out[3] seem to give the correct answer. Why? I am really confused. And how to modify the code to give the expected answer? Thanks!

Appendix: We can test this, for a special case without using Alternatives

   in[8]:= c a[i] x[j] + d f[a[l] x[m]] + f + l +   d a[l] x[n] /. (Longest[u___?(Not[FreeQ[#, a[i_] x[j_]]] &)] + v___) :> (Plus[u])
out[8]= d f[a[l] x[m]] + c a[i] x[j] + d a[l] x[n]

It works here. So the problem really is in Alternatives. FreeQ combined with Alternatives is really confusing, look at these

in[9]:= FreeQ[a x y, a x ]
out[9]= False
in[10]:= FreeQ[a x y, a x | y ]
out[10]= False
in[11]:= FreeQ[a x y, a x | a y ]
out[11]= True

Modify the in[2] a little

in[12]:= termsContain[a + b + c + f[a x y + c] + b x y, { x }]
out[12]= b x y + f[c + a x y]
in[13]:= termsContain[a + b + c + f[a x y + c] + b x y, { a x }]
out[13]=0
in[14]:= termsContain[a + b + c + f[a x y + c] + b x y, { b y }]
out[14]=0

Edit:

At last, I come to this realization,

termsContain[func_, list_] := func /. (Longest[
u___?(Not[And @@ (Through[(FreeQ[#] & /@ list)[#]])] &)] +
v___) :> (Plus[u]);

which is what I want. But I still would like to know how to understand the Alternatives in FreeQ.

format: plain


text:
Yield farming
Here, you will be able to find the most relevant information about yield farming.
The decentralized finance (DeFi) movement has been at the forefront of innovation in the blockchain space. What makes DeFi applications unique? They are permissionless, meaning that anyone (or anything, like a smart contract) with an internet connection and a supported wallet can interact with them. In addition, they typically don’t require trust in any custodians or middlemen. In other words: they are trustless.
Yield farming is a new way to earn rewards with cryptocurrency holdings using permissionless liquidity protocols. It allows anyone to earn passive income using a decentralized ecosystem. Yield farming (also known as liquidity mining) is a way to generate rewards with cryptocurrency holdings. In simple terms, it means locking up cryptocurrencies and getting rewards.

# How it works in DEIP infrastructure

Each F-NFT has metadata. One of the metadata attributes is a category/segment of an underlying intangible asset.
For example, there could be a “technology” category, and the sub-category of “biotech”, “nanotech” or “green tech”.
Every account in the network can stake DEIP tokens on a specific category to increase the amount of funding allocated from the Ecosystem Fund to a specific category of F-NFT. The distribution of capital in the Ecosystem Fund is proportional to the amount of DEIP tokens staked on each specific category.
One of the metadata attributes in every F-NFT is a category/segment of an underlying intangible asset and each F-NFT has a metadata attribute that specifies the platform it is issued on. The metadata attributes allow you to stake DEIP tokens on a particular category to increase the number of funding allocated from the Ecosystem Fund to a specific category of F-NFT. This means that you can stake DEIP tokens to change the distribution of capital allocated for each issuance platform and this increases the platform’s chances of receiving investment from the fund.
Since every F-NFT also has a metadata attribute that specifies the platform it is issued on, it’s possible to stake DEIP tokens to change the distribution of capital allocated for each issuance platform. After network participants have staked their tokens, the Ecosystem Fund will have a special allocation to spend on investments in specific issuance platforms. By default, 5% of the profit from the Ecosystem Fund's investment activities is distributed among those who staked in the category which made this profit.
This creates an incentive to stake DEIP tokens in categories/segments of F-NFTs which will generate the most profits. However, the Council investment decisions and the eventual capital distribution differ from the distribution staked by F-NFT segments. It is like a competition in token staking between the Council and yield farmers. The result of this "competition" is to get investments from the fund and tells us who was better at investment decisions — the Council or the Community of yield farmers.
If the performance of the community is better by {delta} then the next allocation of the DEIP Ecosystem Fund for the community-driven investments will be increased. The initial and minimum percentage of allocated capital for community-driven investment decisions is 20% and the maximum allocation is 80%.
Yield farming by asset segments
The profit from yield farming
$P_{ki}$
for an account i from all accounts [1,N] staked stakes
$ST_i$
with a total amount
$ST$
total on a segment
$k$
is calculated with the formula:
$P_{ki} = \frac{ST_{ki}*\underset{d=day(now)-30}\Sigma P_{kd}}{\sum_{j=1}^{j=N}{ST_{kj}}}$

## Segment Liquidity Pools and AMM

At some point after the network launch when each segment has a considerable amount of DEIP tokens staked on it, the protocol will be updated to convert DEIP tokens staked on a specific segment of assets into a Segment Liquidity Pool (SLP).
Once SLPs are introduced, they will enable additional liquidity for the assets in this segment via automatic market making. An automated market maker (AMM) is a type of decentralized exchange (DEX) protocol that relies on a mathematical formula to price assets. Instead of using an order book like a traditional exchange, assets are priced according to a pricing algorithm.


text:
+0

# is the square root of ten rational or irrational

0
385
2

is the square root of ten rational or irrational

Guest Jan 10, 2015

#1
+26753
+10

Irrational

.

Alan  Jan 10, 2015
#1
+26753
+10

Irrational

.

Alan  Jan 10, 2015
#2
+92805
+5

Lets try and prove this.  I am going to do it by contradiction.

$$\\Assume \;\;\sqrt{10}\; is\; rational\\\\ then \;\sqrt{10}\;can\;\; be\;\; written\;\; as \;\;\dfrac{p}{q}\\ where p and q are relatively prime integers (they have no common factors)\\\\$$

$$\\\sqrt{10}=\frac{p}{q}\\\\ 10=\frac{p^2}{q^2}\\\\ p^2=10q^2\\\\ So\;\; p^2\;\; is a multiple of 10\\\\ \mbox{so p is a multiple of 10}\\\\ Let\; p=10g\\\\ (10g)^2=10q^2\\\\ 100g^2=10q^2\\\\ 10g^2=q^2\\\\ So\;\; q^2  is a multiple of 10\\\\ so q is a multiple of 10\\\\ I have discovered that p and q are both multiples of 10$$\$

Therefore p and q are not relatively prime

therefore the original statement is contradicted

therefore  $${\sqrt{{\mathtt{10}}}}$$    is irrational.

-------------------------------------------------------------

Note:

I have said that since pis a multiple of 10, p must also be a multiple of 10. WHY is so.

Well the prime factors of squared numbers must come in pairs.

Lets look at an example

$$\\What\;\; if\;\; p^2=900\\ p^2=30\times 30\\ p^2=3\times 5\times 2 \quad \times \quad 3\times 5\times 2\\ p^2=3\times 3\times 2 \times 2\times 5\times 5\\ see how the factors have to be in pairs?\\ p=3\times 2 \times 5\\$$

------

10 is the product of 2 prime numbers

Can you see how if  p^2 is a product of 10 then p must also be the product of 10?

Melody  Jan 11, 2015


text:
1. ## closed curve, trace

Let $\displaystyle \gamma$ be a closed path in a domain $\displaystyle D$ such that $\displaystyle W(\gamma, \zeta)=0$ for all $\displaystyle \zeta \not \in D$. Suppose that $\displaystyle f(z)$ is analytic on $\displaystyle D$ except possibly at a finite number of isolated singularities $\displaystyle z_1, \ldots, z_m \in D \char\\ \Gamma$. Show that $\displaystyle \int_{\gamma} f(z)dz = 2 \pi i \sum W(\gamma, \zeta) \text{Res}[f, z_k]$.

Hint

Consider the Laurent decomposition at each $\displaystyle z_k$.

I do not see how to get the Laurent decomposition of the $\displaystyle z_k$ to do this problem. By the way, the above notation means the winding number. It looks like perhaps the residue theorem would come into play here somehow too. I just do not see how to proceed now. Any suggestions would be very nice. Thank you.

2. Originally Posted by poincare4223
Let $\displaystyle \gamma$ be a closed path in a domain $\displaystyle D$ such that $\displaystyle W(\gamma, \zeta)=0$ for all $\displaystyle \zeta \not \in D$. Suppose that $\displaystyle f(z)$ is analytic on $\displaystyle D$ except possibly at a finite number of isolated singularities $\displaystyle z_1, \ldots, z_m \in D \char\\ \Gamma$. Show that $\displaystyle \int_{\gamma} f(z)dz = 2 \pi i \sum W(\gamma, \zeta) \text{Res}[f, z_k]$.

Hint

Consider the Laurent decomposition at each $\displaystyle z_k$.

I do not see how to get the Laurent decomposition of the $\displaystyle z_k$ to do this problem. By the way, the above notation means the winding number. It looks like perhaps the residue theorem would come into play here somehow too. I just do not see how to proceed now. Any suggestions would be very nice. Thank you.
For each $\displaystyle z_j$ consider the set $\displaystyle D_j= \{ z\in \mathbb{C} : 0<|z-z_j|<r_j \}$ where $\displaystyle r_j$ is such that $\displaystyle D_j\cap D_i =\emptyset$ if $\displaystyle i\neq j$. $\displaystyle f$ has a Laurent expansion in each of these (shrink them if necessary) so $\displaystyle f= \sum_{n=0}^{\infty } a_n(z-z_j)^n+ \sum_{n=1}^{\infty } \frac{b_n}{(z-z_j)^n}$. Now define $\displaystyle S_j(z)=\sum_{n=1}^{\infty } \frac{b_n}{(z-z_j)^n}$ then using a dual to Abel's lemma we get that $\displaystyle S_j$ is uniformly convergent in sets of the form $\displaystyle \{ z\in \mathbb{C} : |z-z_j|\geq \epsilon \}$ for all $\displaystyle \epsilon >0$. Now define $\displaystyle g(z)=f(z)-\sum_{k=1}^{m} S_j(z)$ then it's clear that $\displaystyle g$ is holomorphic in $\displaystyle D$ (the $\displaystyle z_i$'s are removable singularities) then $\displaystyle \int_{\gamma } g=0$ (because of Cauchy's theorem and the fact that $\displaystyle \gamma$ is homotopic to a point in $\displaystyle D$) from which $\displaystyle \int_{\gamma } f = \sum_{k=1}^{m} \int_{ \gamma } S_j$. Now to conclude just calculate $\displaystyle \int_{ \gamma } S_j$ where you need to remember this http://www.mathhelpforum.com/math-he...tml#post446504 and that $\displaystyle \int_{\gamma } \frac{1}{z-z_j} = 2\pi i W(\gamma ,z_j)$


text:
DiffBind paired samples
2
0
Entering edit mode
igor ▴ 40
@igor
Last seen 9 months ago
United States

When you run dba.contrast and dba.analyze in DiffBind, it divides the samples into all the possible groups and compares the various groups. If you have paired samples (for example, before and after treatment), is there a way to indicate that so that the analysis takes that into account (rather than simply doing all "before" versus all "after")?

diffbind • 1.0k views
1
Entering edit mode
Gord Brown ▴ 640
@gord-brown-5664
Last seen 8 months ago
United Kingdom

Hi,

The block parameter of dba.contrast allows the sort of paired comparison you want.  See section 5 of the vignette for details.

0
Entering edit mode

I looked at the block parameter. That seems appropriate, but it's fairly flexible. I wasn't sure if there is some other option that specifically assumes paired analysis.

1
Entering edit mode

To the best of my knowledge, block is the only parameter for this purpose.  The EdgeR user manual gives a bit more detail about how to use it.

1
Entering edit mode
Rory Stark ★ 4.1k
@rory-stark-5741
Last seen 1 day ago
CRUK, Cambridge, UK

The block parameter is set up to handle paired samples.  So for example if the CONDITION is before or after, and each pair of samples share the same REPLICATE or TISSUE id, you can try:

myDBA <- dba.contrast(myDBA, group1=myDBA$masks$before, group2=myDBA$masks$after, name1="before",name2="after", block=DBA_REPLICATE)

myDBA <- dba.analyze(myDBA)

myReport <- dba.report(myDBA, method=DBA_EDGER_BLOCK)

0
Entering edit mode

Quick followup. This is your example:

dba.contrast(myDBA, group1=myDBA$masks$before, group2=myDBA$masks$after, name1="before",name2="after", block=DBA_REPLICATE)

Since we only have 2 conditions here, I would do this:

dba.contrast(myDBA, categories=DBA_CONDITION, block=DBA_REPLICATE)

Since you used the less concise approach, are the two actually different? Or was it to make the answer more clear?

0
Entering edit mode

You are correct, I made it very explicit in case you had other conditions, these are the same.

Actually I tend to add each contrast explicitly so I can see the contrasts in my analysis script instead of relying on DiffBind's automatic feature.

-Rory


text:
# Is this related to the j-function?

I was browsing in Plouffe's inverter and found that $\frac{\exp(\pi)-\ln(3)}{\ln(2)}$ is very nearly $\frac{159}{5}.$ The continued fraction is

[31, 1, 4, 12029125, ...].

Is this the same magic as $\exp(\pi \sqrt{163})$?

-
There doesn't seem to be a straightforward relationship with class field theory. See also: xkcd.com/217 –  S. Carnahan May 5 '10 at 1:03

The trick with the modular invariant $j$ is for $\pi\sqrt D$ only (as $j(\pi\sqrt{-D})$ is rational). Your value is not the exponential of a CM-point in the upper halfplane, so nothing to do with modularity. This kind of experimental discoveries already exists in the literature; see, for example, [C. Schneider, R. Pemantle. When is 0.999... equal to 1?. Amer. Math. Monthly 114 (2007) 344-350.].


text:
# Body diagonal

Calculate the length of the body diagonal of the 6cm cube.

Correct result:

u =  10.392 cm

#### Solution:

$a=6 \ \text{cm} \ \\ u=\sqrt{ 3 } \cdot \ a=\sqrt{ 3 } \cdot \ 6=6 \ \sqrt{ 3 }=10.392 \ \text{cm}$

Our examples were largely sent or created by pupils and students themselves. Therefore, we would be pleased if you could send us any errors you found, spelling mistakes, or rephasing the example. Thank you!

Please write to us with your comment on the math problem or ask something. Thank you for helping each other - students, teachers, parents, and problem authors.

Tips to related online calculators
Pythagorean theorem is the base for the right triangle calculator.

#### You need to know the following knowledge to solve this word math problem:

We encourage you to watch this tutorial video on this math problem:

## Next similar math problems:

• Stairway
Stairway has 20 steps. Each step has a length of 22 cm and a height of 15 cm. Calculate the length of the handrail of staircases if on the top and bottom exceeds 10 cm.
• Median in right triangle
In the rectangular triangle ABC has known the length of the legs a = 15cm and b = 36cm. Calculate the length of the median to side c (to hypotenuse).
• Four ropes
TV transmitter is anchored at a height of 44 meters by four ropes. Each rope is attached at a distance of 55 meters from the heel of the TV transmitter. Calculate how many meters of rope were used in the construction of the transmitter. At each attachment
The ladder has a length of 3 m and is leaning against the wall, and its inclination to the wall is 45°. How high does it reach?
• Sailing
Solve the following problem graphically. The fishing boat left the harbor early in the morning and set out to the north. After 12 km of sailing, she changed course and continued 9 km west. Then When she docked and reached the fishing grounds she launched
• Spruce height
How tall was spruce that was cut at an altitude of 8m above the ground and the top landed at a distance of 15m from the heel of the tree?
• Cone 15
The radius of the base of a right circular cone is 14 inches and it's height 18 inches. What is the slant height?
• Center traverse
It is true that the middle traverse bisects the triangle?
The double ladder shoulders should be 3 meters long. What height will the upper top of the ladder reach if the lower ends are 1.8 meters apart?
The double ladder is 8.5m long. It is built so that its lower ends are 3.5 meters apart. How high does the upper end of the ladder reach?
• The double ladder
The double ladder has 3 meters long shoulders. What is the height of the upper of the ladder reach if the lower ends are 1.8 meters apart?
• A truck
A truck departs from a distribution center. From there, it goes 20km west, 30km north and 10km west and reaches a shop. How can the truck reach back to the distribution center from the shop (what is the shortest path)?
• Right angle
If a, b and c are two sides of a triangle ABC, a right angle in A, find the value on each missing side. If b=10, c=6
• Is right triangle
Decide if the triangle XYZ is rectangular: x = 4 m, y = 6 m, z = 4 m
• Right triangles
How many right triangles we can construct from line segments 3,4,5,6,8,10,12,13,15,17 cm long? (Do not forget to the triangle inequality).
• Oil rig
Oil drilling rig is 23 meters height and fix the ropes which ends are 7 meters away from the foot of the tower. How long are these ropes?
• Windbreak
A tree at a height of 3 meters broke in the windbreak. Its peak fell 4.5 m from the tree. How tall was the tree?


text:
# A Day at the Races. Racetrack Betting App

I recently began learning C# and I picked up Head First C# as a starting point. One of the first projects they have you build, without the code provided, is a racetrack betting app. The project first gives you the requirements, as well as some suggested implementations. I did not follow the suggestions too closely though as I think I found some simpler solutions. I would like any and all feedback.

The App looks like this. The greyhounds are currently represented by empty PictureBoxs.

Requirements:

• The four white squares are the greyhounds, each in its own lane.
• There are three RadioButtons which represent the three people at the betting parlor. The selected RadioButton sets the name for the Label on the place bet line.
• There are two NumericUpDowns used to change the amount and dog before clicking the placeBet button.
• Placing a Bet updates the corresponding label for the currently selected individual. A Person can only have one Bet at a time. New Bets override old ones.
• The startRace button starts the race and closes the betting.
• Bets are paid out automatically at the end of the race and then the track is open for betting again.

Form1.cs

using System;
using System.Windows.Forms;

namespace RacetrackApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
minimumBetLabel.Text = "Minimum Bet: " + minimumBet;
Greyhounds[0].AssignPictureBox(dogOne);
Greyhounds[1].AssignPictureBox(dogTwo);
Greyhounds[2].AssignPictureBox(dogThree);
Greyhounds[3].AssignPictureBox(dogFour);

activePerson = People[0];
nameLabel.Text = activePerson.Name;
}

private const int minimumBet = 5;
private bool racing = false;
private Person[] People = { new Person("Joe", 50), new Person("Bob", 75), new Person("Alice", 100) };
private Greyhound[] Greyhounds = { new Greyhound(1), new Greyhound(2), new Greyhound(3), new Greyhound(4) };
private Person activePerson;

private void CheckedChanged(object sender, EventArgs e)
{
if (sender as RadioButton == personOne)
{
activePerson = People[0];
}
else if (sender as RadioButton == personTwo)
{
activePerson = People[1];
}
else
{
activePerson = People[2];
}

nameLabel.Text = activePerson.Name;
}

private void PlaceBet_Click(object sender, EventArgs e)
{
if (!racing)
{
activePerson.MakeBet((int)betNumber.Value, Greyhounds[(int)dogNumber.Value - 1]);
}
}

private void StartRace_Click(object sender, EventArgs e)
{
if (!racing)
{
racing = true;
timer1.Start();
}
}

private void Timer1_Tick(object sender, EventArgs e)
{
foreach (Greyhound greyhound in Greyhounds)
{
if (greyhound.Run())
{
EndRace(greyhound);
break;
}
}
}

private void EndRace(Greyhound winningGreyhound)
{
foreach (Person person in People)
{
person.CheckBet(winningGreyhound);
}
foreach (Greyhound greyhound in Greyhounds)
{
greyhound.ReturnToStart();
}
timer1.Stop();
racing = false;
}
}
}

Form1 just holds the objects and maintains the Interface interactions.

Person.cs

using System.Windows.Forms;

namespace RacetrackApp
{
public class Person
{
public Person(string name, int cash)
{
Name = name;
Cash = cash;
}

public string Name { get; }
public int Cash { get; private set; }
public Bet Bet { get; private set; }

public Label MyLabel { get; private set; }

{
MyLabel = label;

MyRadioButton.Text = Name + " has $" + Cash; MyLabel.Text = null; } public void MakeBet(int amount, Greyhound greyhound) { if (!(Bet is null)) { Cash += Bet.Amount; } Cash -= amount; Bet = new Bet(amount, greyhound); MyLabel.Text = Name + " bets$" + Bet.Amount + " on Dog " + greyhound.IDNumber;
}

public void CheckBet(Greyhound greyhound)
{
if (!(Bet is null))
{
if (greyhound == Bet.Greyhound)
{
Cash += Bet.Amount * 2;
}
MyRadioButton.Text = Name + " has $" + Cash; Bet = null; MyLabel.Text = null; } } } }  Person maintains private state, like name, cash, an instance of Bet and reference to the UI elements directly related to them. Bet.cs namespace RacetrackApp { public class Bet { public Bet(int amount, Greyhound greyhound) { Amount = amount; Greyhound = greyhound; } public int Amount { get; } public Greyhound Greyhound { get; } } }  Bet is a simple data struct that is declared as a class so it can be nulled Greyhound.cs using System; using System.Drawing; using System.Windows.Forms; namespace RacetrackApp { public class Greyhound { public Greyhound(int ID) => IDNumber = ID; public PictureBox PictureBox { get; private set; } public int IDNumber { get; } private static readonly Random random = new Random(); private const int StartingLine = 12; private const int FinishLine = 875; private const int MinSpeed = 10; private const int MaxSpeed = 35; public void AssignPictureBox(PictureBox pictureBox) => PictureBox = pictureBox; public void ReturnToStart() { int YLocation = PictureBox.Location.Y; PictureBox.Location = new Point(StartingLine, YLocation); } public bool Run() { int XLocation = random.Next(PictureBox.Location.X + MinSpeed, PictureBox.Location.X + MaxSpeed); int YLocation = PictureBox.Location.Y; if (XLocation > FinishLine) { XLocation = FinishLine; PictureBox.Location = new Point(XLocation, YLocation); return true; } PictureBox.Location = new Point(XLocation, YLocation); return false; } } }  Greyhound has a reference to it's own image (which is currently blank) and then, using Random, moves across the track. The Run() method returns true when the greyhound crosses the finish line. This is the thing I am least satisfied with my solution. If two dogs would both cross the finish line within the same tick the one that wins is the one that is indexed lower in the array. I chose this solution because I did not want to have ties and I can't imagine a tie-breaking system that wasn't too sophisticated for this simple exercise. I look forward to anything you can tell me to help with my approach to C#. • Your race only has 2^32 possible sequences. This is because of the static Random instance and all arguments to .Next() are deterministic. This is generally a good thing for testing, but not if you want truly random races every time. – Brad M Jan 23 at 19:23 • @BradM thank you for that truly useful observation. More importantly, would this effect the probability of one dog winning the race over there others? – bruglesco Jan 23 at 19:42 • "Probability" isn't the best word to describe this code because it is 100% deterministic based on the random seed (the default is the system timestamp). Using the Random class properly is deceptively complex for other reasons as well. – Brad M Jan 23 at 20:05 • @BradM I was worried you would say that when you mentioned it was deterministic. Thank you. Sounds like something worthwhile for me to look into. – bruglesco Jan 23 at 20:10 • Check out my approach is shuffling a list inside /src/core/Utilities.cs. It should give some insight into handling these scenarios. github.com/bradmarder/MSEngine – Brad M Jan 23 at 20:16 ## 1 Answer Some things you might like to think about. (Please don't be disheartened. Most of this is picky). I'd like to see the people and the greyhounds more separated from the form used for display. There's no real reason for a greyhound to know anything about a picture box for example - it should know how far it's run, then the form draws the picture box using that information. This is probably not something to worry much about at this stage in your learning, but as you write more programs, you'll thank yourself for keeping business/game logic and presentation separate. (I'm not familiar with the book you're using by the way, but it sounds like it has fun examples/exercises). However, given that you are letting the form run everything, I note that the Assign methods (particularly AssignPictureBox) are really just setters. Greyhound.PictureBox might just as well have public get and set if you're going to provide a method to set it anyway. (I like that you're trying to use encapsulation to keep the setter private, but if a method exists to set it anyway, encapsulation isn't working - let it be a public setter, if that's what it honestly is. It works much better for Person.Cash for example, where the setter is rightly private - nothing outside should be able to set how much cash a person has, only give or take cash when they win or lose a bet, so a private set is absolutely correct there). Bet is good, I like that it's immutable. Just a thought while I'm looking at it: the usual data type for currency is decimal, rather than int (what if someone wants to bet$5.75?). No big deal, but it'd be a good habit to get into.

Personally I vastly prefer using var whenever possible (i.e. local variables), for example foreach (var person in People). There are good reasons for this (particularly making it easier to change the type of something without having to update everywhere it's used), though some people think it obscures information from the programmer and prefer not to use it. I think that misses the point, but I won't repeat the flame war about it here, just something for you to read about and make up your own mind. :-)

I really like that you're naming your controls (if I ever again have to try to work out what button1 does or what gets entered into textBox2, I'll scream) but I would recommend including what the control is in the name. personOne doesn't sound like a radio button, personOneRadioButton does, and it's easily distinguishable from personOneLabel and personOneTextBox, if such things existed.

CheckedChanged could definitely be improved by adding the Person as a Tag on the radio button. So, in your initialization code you'd do something like this:

personOneRadioButton.Tag = People[0];
...

Then, CheckedChanged doesn't need all those ifs and ass, and becomes simply:

var rb = (RadioButton)sender;
activePerson = (Person)(rb.Tag);
nameLabel.Text = activePerson.Name;

Unless I'm missing something, a person can make a bet they don't actually have enough money for? :-D Also, you don't show the generated code for the controls (which is fine), but I hope the betNumber NumericUpDown has a MinValue of 0, to prevent people placing negative bets and hoping they lose, right? :-D

I like that you've thought about how to handle ties, or at least are aware of it. An alternative approach might be to let all the greyhounds run in every tick, then at the end of Timer1_Tick, look for the greyhound with the largest X position and award them the win if they're past the finish line. (Ties would still be possible, and could be resolved however you see fit, but currently the greyhounds near the top of the track get more chances to win. If this were gambling real money, punters would not like that!)

Greyhound.Run() is a little messy. There's a bit of code duplication, and the distance the greyhound ran that tick is mixed up with the picture box stuff, and two returns where there could be just one... looks like it works fine, but it could be cleaner. Something like:

var distanceRan = random.Next(MinSpeed, MaxSpeed);
var newX = Math.Max(PictureBox.Location.X + distanceRan, FinishLine);
PictureBox.Location = new Point (newX, PictureBox.Location.Y);
return newX >= FinishLine;

(Given the suggestion above about deciding who wins, the Math.Max didn't ought to be necessary, nor returning a bool of whether the greyhound has won or not; but I wanted to demonstrate changing only the way the method is laid out (neater IMO), not what it does.)

On the use of Random (as it was mentioned in the comments): personally I think what you've done is fine as-is. The clock is used as a seed in new Random() so it's not like every race will be the same, and there's no way to predict the outcome. It is very common for games to make sure a different seed is used each playthrough, but for everything after that to be deterministic - it helps with testing, replays, online multiplayer synchronization, etc. So I think it's fine. However, you may decide that for fairness or other reasons, that's not enough for you. In that case, you could use a new random seed each race, or for each greyhound, instead of just once.

Hope this helps.


text:
Latest news 2020-07-03: SmashWords sale (ends 31st July 2020): 50% off crime/SF novel The Private Enemy and 100% off (free!) I’ve Heard the Mermaid Sing.

# Bug Tracker

ID: 20 🔗 Closed (Fixed) datatool 2.13 18 2013-01-18 11:12:26 Error if \DTLnewdbentry's third argument is an empty macro

## Report

Hi,

the bug nr 18 (xkeyval incompatibility) has in fact nothing to do with xkeyval (sorry).

It appears that if \DTLnewdbentry's third argument (value of the identifier key) is an empty macro, the following error occurs:

Runaway argument?
\@nil \ifnum \@dtl@numgrpsepcount >-1\relax \if@dtl@numgrpsep \ifnum \ETC.
! File ended while scanning use of \@dtl@checknumericalstart.

The joind MCE shows the problem:

  \DTLnewdbentry{mydata}{Surname}{\test}%

is OK as long as \test is a non-empty macro.

### MWE

\documentclass{article}
\usepackage{datatool}
%
\newcommand{\test}{}
%
\begin{document}
%
\DTLnewdb{mydata}%
%
\renewcommand{\test}{Doe}
\DTLnewrow{mydata}%
\DTLnewdbentry{mydata}{Surname}{\test}%
%
\renewcommand{\test}{}
\DTLnewrow{mydata}%
\DTLnewdbentry{mydata}{Surname}{\test}%
\end{document}

## Evaluation:

This is now fixed in version 2.14.

## Watch This Report

If you supply your name, it will be used in the email greeting, which provides a more personal message, otherwise you'll just get a generic greeting. If you have previously supplied your name when signing up for notifications, you don't need to resupply it unless you want to change it.

If you have previously subscribed to notifications for this report, you can unsubscribe by clicking on the "Stop Notification" button.

The "Confirm Bug ID" field helps to protect against spambots. Please enter the bug ID (which you can find at the top of this page).

Name: (Optional.)