Menu Close

Statistical software: UPSC Statistics Optional PYQ Solutions (1996–2026)

All 16 questions UPSC has asked on statistical software in the Statistics Optional (Paper II, Optimization Techniques) from 1996 to 2026, solved step by step – latest first.

Try them yourself first: the same questions, without solutions, are on our Optimization Techniques topic-wise PYQs page.

How we check these solutions

These are our own solutions, prepared with AI help. UPSC does not publish official answers. Every solution is checked a second way before it goes up, and says how:

  • ✓ Checked by computer the numbers were worked out again independently in code (Python with NumPy/SciPy) and matched.
  • ✓ Answer checked step by step for descriptive questions, every point was checked against the standard theory.

Spotted a mistake or a neater method? Tell us in the comments below or through Report an error.

Jump to a question (year · question number):

2026 · 1e 2007 · 3c 2006 · 4d 2005 · 4d 2004 · 4d 2003 · 4d 2002 · 4d 2001 · 4d 1998 · 12a 1998 · 12b 1998 · 12c 1997 · 12a 1997 · 12b 1997 · 12c 1996 · 12b 1996 · 12c

Cover of the UPSC Prelims Topic-wise PYQ book with detailed explanations

From the Optional Province team

Preparing for Prelims too?

Our UPSC Prelims Topic-wise PYQ Book covers every Prelims question with detailed explanations, so you can see exactly where UPSC asks from. Now available as a hard copy and an eBook.

Buy Hard Copy on AmazonBuy eBook (PDF)

Download a free sample

What are the key features of SPSS software? How does it compare to R software?

2026 · Paper II · Q1e · 10 marks

Solution

SPSS (Statistical Package for the Social Sciences, now IBM SPSS Statistics) is a menu-driven package for managing and analysing data, widely used in social science, market research, health and education.

Key features of SPSS.

  1. Two views of the data: Data View (a spreadsheet of cases × variables) and Variable View (name, type, labels, value labels, missing-value codes, measurement level).
  2. Point-and-click menus and dialog boxes for almost every procedure, so analyses can be run without programming; every action can also be pasted as syntax (a command language) for documentation and repetition.
  3. Data management: import from Excel, CSV, databases; recode, compute, select and weight cases, merge and split files, handle missing values.
  4. Wide range of procedures: descriptive statistics, cross-tabulation and chi-square, t-tests, ANOVA and general linear models, correlation, linear/logistic/nonlinear regression, factor and cluster analysis, discriminant analysis, non-parametric tests, reliability analysis, time series, survival analysis; add-on modules for advanced methods (complex samples, missing values, structural equations through AMOS).
  5. Output Viewer with formatted tables and charts (Chart Builder), exportable to Word, Excel and PDF.
  6. Easy to learn, with good documentation and technical support.

Comparison with R.

Point SPSS R
Cost and licence Commercial, paid licence Free and open source
Interface Menus and dialogs (plus syntax) Mainly command/script based (RStudio helps)
Learning curve Gentle; suits non-programmers Steeper; needs programming
Range of methods Standard methods, fixed set; add-ons cost extra Very wide; over 20,000 packages; new methods appear first in R
Flexibility Limited customisation Fully programmable; users write their own functions and simulations
Graphics Standard charts, easy to make Highly flexible, publication-quality (ggplot2)
Reproducibility Syntax files Scripts, R Markdown/Quarto reports
Big data and integration Moderate Connects to databases, Python, C++, cloud; handles large data with packages
Support Vendor support Community support and documentation

In short: SPSS is convenient for routine analysis by users who prefer menus; R is more powerful, flexible and free, and better for research, simulation and new methods, at the price of learning to program.

✓ Answer checked step by step Every point was checked against the documented features of IBM SPSS Statistics and of R.

↑ Back to the question list

Discuss some statistical problems which can be solved by using well known Statistical Software Packages like SPSS and which otherwise are difficult to solve.

2007 · Paper II · Q3c · 15 marks

Solution

Statistical software packages such as SPSS make it possible to solve problems that involve large data sets, heavy computation, iterative estimation or many variables, which are tedious or practically impossible by hand. Some examples:

  1. Multiple regression with many variables — computing β̂=(X′X)−1X′y\hat\beta=(X'X)^{-1}X'y needs inversion of a p×pp\times p matrix; with stepwise selection, diagnostics (residual plots, VIF for multicollinearity, Cook’s distance) and many observations, this is only practical by computer (Analyze → Regression → Linear).

  2. Logistic, probit and other nonlinear regressions — the maximum likelihood estimates have no closed form and are found by iterative methods (Newton–Raphson); SPSS does this automatically.

  3. Multivariate analysis — factor analysis and principal components (eigenvalues of large correlation matrices, rotations), cluster analysis (distance matrices for hundreds of cases), discriminant analysis, MANOVA, canonical correlation.

  4. Analysis of variance for complex designs — factorial designs with interactions, unbalanced data, repeated measures, covariance analysis (General Linear Model), with post-hoc multiple comparisons.

  5. Large surveys — cleaning and recoding thousands of records, cross-tabulations with chi-square tests, weighting, and complex sample designs (strata, clusters) for correct standard errors.

  6. Non-parametric tests on large samples — exact pp-values for Mann–Whitney, Kruskal–Wallis, Wilcoxon, Friedman tests, which need extensive tabulation by hand.

  7. Time series — fitting ARIMA models, exponential smoothing and seasonal decomposition, and forecasting; these require iterative estimation.

  8. Survival analysis — Kaplan–Meier curves and Cox proportional hazards regression with censored data.

  9. Reliability and scale analysis — Cronbach’s alpha and item analysis for questionnaires.

  10. Simulation and resampling — generating random samples from distributions to study the sampling distribution of a complicated statistic, and bootstrap confidence intervals, which have no exact theory (see Q4).

  11. Graphical analysis — histograms, box plots, normal probability (Q–Q) plots and scatter-plot matrices for checking assumptions.

The package removes arithmetic errors, gives results quickly, and lets the statistician concentrate on choosing the right model and interpreting the output.

✓ Answer checked step by step Every point was checked: each listed problem is one whose hand computation is impractical and which SPSS handles through a standard procedure.

↑ Back to the question list

Describe the use of SPSS software packages with an illustration.

2006 · Paper II · Q4d · 15 marks

Solution

Uses of SPSS. SPSS is used to enter, manage and analyse data and to present the results: descriptive statistics and frequency tables; cross-tabulations and chi-square tests; tt-tests and ANOVA; correlation and regression; non-parametric tests; multivariate methods (factor, cluster, discriminant analysis); time series and survival analysis; and charts. It is used in surveys, market research, social science, education, health and quality control.

Working in SPSS — the steps.

  1. Define variables in Variable View (name, type, labels, value labels, missing values, measure).
  2. Enter or import data in Data View (each row a case, each column a variable), or open an Excel/CSV file.
  3. Prepare data — Transform → Compute/Recode; Data → Select Cases, Sort, Merge.
  4. Choose the analysis from the Analyze menu and set options in the dialog box.
  5. Read the Output Viewer — tables and charts; export them to Word or PDF.
  6. Optionally paste the syntax to keep a record and re-run the analysis.

Illustration: correlation and regression. A firm records advertising spend xx (₹ thousand) and sales yy (₹ lakh) for 10 months:

xx 10 12 15 17 20 22 25 27 30 32
yy 36 40 46 49 54 58 62 66 72 76
  • Enter two variables, ADV and SALES, with 10 cases.
  • Analyze → Correlate → Bivariate (Pearson): r=0.999r=0.999 (SPSS reports rr, the two-sided pp-value and nn).
  • Analyze → Regression → Linear, Dependent = SALES, Independent = ADV. The output gives the Model Summary (RR, R2R^2), the ANOVA table (FF test), and the Coefficients table (constant, slope, standard errors, tt, pp), plus residual plots if requested.

Equivalent syntax:

CORRELATIONS /VARIABLES=ADV SALES /PRINT=TWOTAIL.
REGRESSION /DEPENDENT SALES /METHOD=ENTER ADV
  /SCATTERPLOT=(*ZRESID,*ZPRED).

The output shows a very strong positive relationship (p<0.001p<0.001), and the fitted line SALEŜ=18.68+1.77ADV\widehat{\text{SALES}}=18.68+1.77\,\text{ADV} (R2=0.998R^2=0.998) can be used to predict sales for a planned advertising budget.

✓ Answer checked step by step We checked the illustration in Python: for the 10 pairs shown, Pearson r = 0.999, the regression line is ŷ = 18.68 + 1.77x, and the t-test of β = 0 has p < 0.001.

↑ Back to the question list

Let X1,X2,…,Xn be a random sample from an N(μ,σ2) distribution (μ, σ2 known). Let T=∑i=120Xi5/2e−2xi1/2 [?] be a statistic. Explain how the well-known statistical software packages like SPSS can be used to find the distribution of T.

2005 · Paper II · Q4d · 15 marks

Solution

Note on the question. The statistic is printed with a lower-case xix_i and a sum to 20; we read it as T=∑i=120Xi5/2e−2Xi1/2,T=\sum_{i=1}^{20}X_i^{5/2}e^{-2X_i^{1/2}}, with n=20n=20. The powers X5/2X^{5/2} and X1/2X^{1/2} are real only for X≥0X\ge0, so we take μ\mu large compared with σ\sigma (so that negative values practically never occur), or use |Xi||X_i|.

Why software is needed. TT is a sum of a complicated non-linear function of normal variables. Its exact distribution has no closed form. But because μ\mu and σ2\sigma^2 are known, we can simulate it: generate many samples of size 20 from N(μ,σ2)N(\mu,\sigma^2), compute TT for each, and study the resulting values. This Monte Carlo method approximates the sampling distribution as closely as we like (with BB replications, the error in a probability is about p(1−p)/B\sqrt{p(1-p)/B}).

Steps in SPSS.

  1. Create the replications. Make a data file with BB cases (say B=10,000B=10{,}000), one per simulated sample, e.g. with an INPUT PROGRAM loop.
  2. Generate the sample. For each case compute 20 normal variables with the random-number function RV.NORMAL(mu, sigma) (Transform → Compute Variable, or syntax), after fixing the seed for reproducibility (SET SEED).
  3. Compute TT for each case with COMPUTE, using ** for powers and EXP.
  4. Study the distribution of TT — Analyze → Descriptive Statistics → Frequencies/Explore: mean, standard deviation, skewness, kurtosis, percentiles, histogram with a normal curve, Q–Q plot; Kolmogorov–Smirnov test (Nonparametric Tests) against a normal or other fitted distribution.
  5. Use it — e.g. read off the 5% and 95% points of TT as critical values, or estimate P(T>t0)P(T>t_0) by the proportion of simulated values above t0t_0.

Illustrative syntax (μ=4\mu=4, σ=1\sigma=1):

SET SEED=12345.
INPUT PROGRAM.
LOOP #REP=1 TO 10000.
  COMPUTE T=0.
  LOOP #I=1 TO 20.
    COMPUTE X=RV.NORMAL(4,1).
    COMPUTE T=T + ABS(X)**2.5 * EXP(-2*ABS(X)**0.5).
  END LOOP.
  END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.
FREQUENCIES VARIABLES=T /FORMAT=NOTABLE
  /PERCENTILES=2.5 5 50 95 97.5
  /STATISTICS=MEAN STDDEV SKEWNESS KURTOSIS
  /HISTOGRAM NORMAL.

What to expect. Since TT is a sum of 20 i.i.d. terms, by the central limit theorem its distribution will be close to normal, with mean 20E[g(X)]20\,E[g(X)] and variance 20Var[g(X)]20\operatorname{Var}[g(X)], where g(x)=x5/2e−2xg(x)=x^{5/2}e^{-2\sqrt x}; the simulation confirms this and measures any skewness. (In our check with μ=4\mu=4, σ=1\sigma=1, 100,000 simulated values of TT had mean about 11.27 and s.d. about 0.38, with slight negative skewness; negative XX occurred in only 0.003% of draws.)

✓ Answer checked step by step We checked the method in Python by simulating 100,000 values of T for μ = 4, σ = 1 and n = 20, the same steps the SPSS syntax carries out.

↑ Back to the question list

What are SPSS packages? Explain their uses.

2004 · Paper II · Q4d · 15 marks

Solution

What SPSS is. SPSS (Statistical Package for the Social Sciences), first developed in 1968 by Nie, Hull and Bent and now sold as IBM SPSS Statistics, is an integrated set of programs (“package”) for data management and statistical analysis. It consists of a base system and optional modules, works through menus or its own command syntax, and produces formatted tables and charts.

Components (packages/modules).

  • SPSS Statistics Base — data handling, descriptive statistics, cross-tabs, tt-tests, ANOVA, correlation, linear regression, factor and cluster analysis, non-parametric tests, charts.
  • Advanced and Regression modules — GLM and mixed models, logistic and nonlinear regression, survival analysis.
  • Others — Forecasting (time series), Categories (correspondence analysis), Complex Samples, Missing Values, Exact Tests, Custom Tables; AMOS for structural equation modelling; SPSS Modeler for data mining.

Uses.

  1. Data management — data entry, coding, cleaning, recoding, computing new variables, merging files, handling missing data.
  2. Descriptive analysis — frequency tables, measures of central tendency and dispersion, cross-tabulations, graphs.
  3. Testing hypotheses — tt, FF, chi-square and non-parametric tests with exact pp-values.
  4. Modelling relationships — correlation, simple and multiple regression, logistic regression, ANOVA/ANCOVA.
  5. Multivariate analysis — factor, cluster, discriminant, canonical analysis, MANOVA.
  6. Forecasting — time-series smoothing and ARIMA models.
  7. Survey and market research — questionnaire analysis, reliability (Cronbach’s alpha), weighting, tabulation.
  8. Quality control and health research — control charts, survival analysis.
  9. Reporting — exporting publication-quality tables and charts.

Its value lies in speed, accuracy, ease of use and the ability to handle large data sets and complex methods.

✓ Answer checked step by step Every point was checked against the documented components and procedures of SPSS.

↑ Back to the question list

Describe the salient features of the SPSS package. Explain how to find a multiple linear regression based on p independent variables and n (≥p) observations.

2003 · Paper II · Q4d · 15 marks

Solution

Salient features of SPSS.

  1. Data Editor with Data View and Variable View; variable and value labels; missing-value codes.
  2. Menu-driven analysis with dialog boxes, plus a command syntax language (Paste button) for automation and records.
  3. Data transformation — compute, recode, select, sort, merge, aggregate, weight cases.
  4. Comprehensive statistics — descriptive, inferential, regression, ANOVA/GLM, multivariate, non-parametric, time series, survival.
  5. Output Viewer — pivot tables and charts that can be edited and exported.
  6. Graphics — Chart Builder for bar, line, pie, histogram, scatter, box plots.
  7. Import/export with Excel, CSV, databases, other packages.
  8. Extensible through modules and integration with Python and R.

Multiple linear regression with pp independent variables and n(≥p)n\ (\ge p) observations. (For the coefficients to be estimable we need n>pn>p; in fact n≥p+2n\ge p+2 to estimate the error variance and test the model.)

Model: yi=β0+β1x1i+…+βpxpi+εi,εi∼N(0,σ2),y_i=\beta_0+\beta_1x_{1i}+\dots+\beta_px_{pi}+\varepsilon_i,\qquad\varepsilon_i\sim N(0,\sigma^2), i.e. y=Xβ+εy=X\beta+\varepsilon, with least squares estimate β̂=(X′X)−1X′y\hat\beta=(X'X)^{-1}X'y.

Steps in SPSS:

  1. Enter the data: one row per observation; columns YY, X1,…,XpX_1,\dots,X_p.
  2. Analyze → Regression → Linear.
  3. Put YY in Dependent and X1,…,XpX_1,\dots,X_p in Independent(s). Method: Enter (all variables), or Stepwise/Forward/Backward for variable selection.
  4. Statistics: estimates, confidence intervals, model fit, R2R^2 change, descriptives, collinearity diagnostics, Durbin–Watson. Plots: ZRESID vs ZPRED, normal probability plot of residuals. Save: predicted values, residuals, Cook’s distance.
  5. Click OK (or paste the syntax):
REGRESSION
  /STATISTICS COEFF OUTS CI(95) R ANOVA COLLIN
  /DEPENDENT Y
  /METHOD=ENTER X1 X2 X3
  /RESIDUALS DURBIN NORMPROB(ZRESID)
  /SCATTERPLOT=(*ZRESID,*ZPRED).

Reading the output:

  • Model Summary — RR, R2R^2, adjusted R2R^2, standard error of the estimate σ̂\hat\sigma.
  • ANOVA — regression and residual sums of squares; F=SSR/pSSE/(n−p−1)F=\dfrac{SSR/p}{SSE/(n-p-1)} tests H0:β1=…=βp=0H_0:\beta_1=\dots=\beta_p=0.
  • Coefficients — β̂j\hat\beta_j, standard errors, standardised betas, t=β̂j/SE(β̂j)t=\hat\beta_j/SE(\hat\beta_j) with n−p−1n-p-1 d.f. and pp-values; VIF for multicollinearity.
  • Residual plots — check linearity, constant variance and normality.

The fitted equation ŷ=β̂0+β̂1x1+…+β̂pxp\hat y=\hat\beta_0+\hat\beta_1x_1+\dots+\hat\beta_px_p is then used for interpretation and prediction.

✓ Answer checked step by step We checked the regression set-up on simulated data in Python (n = 30, p = 3): the normal-equation solution (X′X)⁻¹X′y matched a standard least-squares routine, as SPSS’s REGRESSION output would.

↑ Back to the question list

Explain the use of SPSS package in solving statistical problems. In particular, how will you carry out two-way analysis of variance for a given data by using SPSS?

2002 · Paper II · Q4d · 15 marks

Solution

Use of SPSS in solving statistical problems. SPSS turns a statistical problem into a sequence of simple steps: define the variables, enter or import the data, choose the procedure from the Analyze menu, set options, and interpret the formatted output. It handles large data sets, does the computation exactly and quickly, checks assumptions (normality, equal variances) with tests and plots, and covers most standard methods — descriptive statistics, tests of significance, ANOVA, regression, multivariate and non-parametric methods, time series.

Two-way analysis of variance in SPSS. Suppose yield YY is observed for 3 fertilisers (factor A) and 2 varieties (factor B), with rr replicates per cell. Model: yijk=μ+αi+βj+(αβ)ij+εijk.y_{ijk}=\mu+\alpha_i+\beta_j+(\alpha\beta)_{ij}+\varepsilon_{ijk}.

  1. Data entry (long format): three columns — FERT (codes 1–3), VARIETY (codes 1–2) and YIELD — one row per observation. Add value labels to the codes.
  2. Analyze → General Linear Model → Univariate.
  3. Dependent Variable: YIELD; Fixed Factor(s): FERT and VARIETY (use Random Factor(s) for random effects).
  4. Model: Full factorial (main effects + interaction). With one observation per cell, choose Custom with main effects only (the interaction is then the error).
  5. Post Hoc: Tukey/Scheffé/LSD for FERT; Plots: FERT × VARIETY profile (interaction) plot; Options: descriptive statistics, estimates of effect size, homogeneity test (Levene).
  6. Click OK. Equivalent syntax:
UNIANOVA YIELD BY FERT VARIETY
  /METHOD=SSTYPE(3)
  /DESIGN=FERT VARIETY FERT*VARIETY
  /POSTHOC=FERT(TUKEY)
  /PLOT=PROFILE(FERT*VARIETY)
  /PRINT=DESCRIPTIVE HOMOGENEITY ETASQ.

Interpreting the output. The Tests of Between-Subjects Effects table gives, for FERT, VARIETY, FERT*VARIETY and Error: the sums of squares, d.f. (a−1a-1, b−1b-1, (a−1)(b−1)(a-1)(b-1), ab(r−1)ab(r-1)), mean squares, FF ratios and significance (pp-values). We first look at the interaction: if it is not significant, we interpret the main effects; if it is significant, we compare treatment means within each level of the other factor (simple effects) using the profile plot. Post-hoc tests then show which fertilisers differ.

✓ Answer checked step by step Every point was checked against SPSS’s GLM Univariate (UNIANOVA) procedure and the two-way ANOVA model with interaction, including the degrees of freedom in the output table.

↑ Back to the question list

Write briefly on the software package SPSS.

2001 · Paper II · Q4d · 15 marks

Solution

SPSS (originally Statistical Package for the Social Sciences; now IBM SPSS Statistics) is one of the oldest and most widely used statistical software packages. It was developed in 1968 at Stanford by Norman Nie, Dale Bent and Hadlai Hull, was acquired by IBM in 2009, and runs on Windows, macOS and Linux.

Structure. A Data Editor (Data View for cases × variables, Variable View for definitions), a Syntax Editor for its command language, and an Output Viewer for tables and charts. Analyses are chosen from menus (Analyze, Graphs, Transform) or written as syntax.

Capabilities.

  • Data management: import/export (Excel, CSV, databases), recoding, computing, selecting, merging, weighting, missing values.
  • Statistics: descriptives, frequencies, cross-tabs and chi-square, tt-tests, ANOVA and GLM, correlation, linear/logistic/nonlinear regression, factor, cluster and discriminant analysis, reliability, non-parametric tests, time series, survival analysis.
  • Graphics: Chart Builder for all common charts.
  • Extensions: add-on modules, Python/R integration, AMOS (structural equations).

Merits. Easy to learn and use; no programming needed; reliable, well-documented procedures; good presentation of output; handles large data sets; syntax allows repeatable analysis.

Limitations. Costly licence; less flexible than programming languages such as R or SAS for new or non-standard methods; some advanced methods need extra modules; users may run procedures without understanding the assumptions.

SPSS is widely used in social sciences, market research, health, education and government statistics.

✓ Answer checked step by step Every point was checked against the documented features and history of SPSS.

↑ Back to the question list

Cover of the UPSC Mains Topic-wise and Year-wise PYQs book (2013–2026)

From the Optional Province team

Strengthen your GS papers

Our UPSC Mains Topic-wise & Year-wise PYQ Book (2013–2026) maps every GS question to the syllabus, so you know what UPSC asks and how often. Now available as a hard copy and an eBook.

Buy Hard Copy on AmazonBuy eBook (PDF)

Download a free sample

Describe the inter-relation amongst machine language, FORTRAN compiler, the FORTRAN source program and object code.

1998 · Paper II · Q12a · 20 marks

Solution

Machine language is the set of binary instructions that a particular computer’s processor executes directly. It is the only language the hardware understands.

FORTRAN source program is the program written by the user in FORTRAN (a high-level language) — statements such as X = A + B*C or DO 10 I = 1, N. The computer cannot execute it directly.

FORTRAN compiler is a system program (itself in machine language) that translates the whole source program into machine language. It also checks the syntax and reports errors (compile-time diagnostics), allocates storage for variables and arrays, and optimises the code.

Object code (object program) is the machine-language output of the compiler. It is then linked (by a linker/loader) with library routines (e.g. SQRT, SIN, input/output routines) to form an executable program, which is loaded into memory and run on the data.

Inter-relation.

FORTRAN source program --(input to)--> FORTRAN compiler
                                         | translates
                                         v
library routines --(linker)--> object code (machine language)
                                         |
                                         v
                       executable program --> run with data --> results
  • The source program is the input to the compiler; the object code is its output.
  • The object code is in machine language, so the computer can execute it after linking and loading.
  • The compiler translates once; the object program can be run many times without re-compiling. Changing the source requires re-compiling.
  • Errors: syntax errors are found by the compiler; logical and run-time errors appear only when the object program runs.

(In contrast, an interpreter translates and executes one statement at a time and produces no object code.)

✓ Answer checked step by step Every point was checked against the standard description of compiling and linking a FORTRAN program.

↑ Back to the question list

Write a note on library functions available in FORTRAN IV.

1998 · Paper II · Q12b · 20 marks

Solution

Library functions in FORTRAN are built-in (intrinsic or supplied) subprograms that compute standard mathematical and conversion functions. They are used by writing the function name with its argument(s) in an expression, e.g. Y = SQRT(X) + ALOG(Z). The compiler links the corresponding routine from the system library. In FORTRAN IV the type of the function is fixed by its name: names beginning with I–N return integers, others real; double-precision versions begin with D, complex versions with C.

Common FORTRAN IV library functions.

Function Name (real) Double precision Integer / other
Square root x\sqrt x SQRT(X) DSQRT —
Exponential exe^x EXP(X) DEXP —
Natural log lnx\ln x ALOG(X) DLOG —
Common log log10x\log_{10}x ALOG10(X) DLOG10 —
Sine, cosine (radians) SIN(X), COS(X) DSIN, DCOS —
Tangent TAN(X) (later versions) DTAN —
Arc tangent ATAN(X), ATAN2(Y,X) DATAN —
Hyperbolic tangent TANH(X) DTANH —
Absolute value ABS(X) DABS IABS(I)
Maximum / minimum AMAX1, AMIN1 DMAX1, DMIN1 MAX0, MIN0
Remainder AMOD(X,Y) DMOD MOD(I,J)
Transfer of sign SIGN(X,Y) DSIGN ISIGN
Positive difference DIM(X,Y) — IDIM
Truncation AINT(X) — INT(X), IFIX(X)
Type conversion FLOAT(I) (integer → real) DBLE(X), SNGL(D) IFIX(X) (real → integer)
Complex REAL(C), AIMAG(C), CMPLX(X,Y), CONJG(C), CABS(C)

Rules for use.

  1. The argument must be of the correct type and in the valid range (e.g. SQRT and ALOG need non-negative / positive arguments; trigonometric functions use radians).
  2. Arguments may be constants, variables, expressions or other function references: Z = EXP(-X*X/2.0)/SQRT(2.0*3.14159).
  3. The function name must not be used as a variable name in the same program unit.
  4. A function returns a single value and can appear wherever an expression of that type can.

(FORTRAN 77 later introduced generic names, so LOG, SQRT, ABS, MAX work for any numeric type.)

Example. The normal density at x=1.5x=1.5:

      X = 1.5
      F = EXP(-X*X/2.0) / SQRT(2.0*3.14159265)
      WRITE (6,10) X, F
   10 FORMAT (1X, 'F(', F4.1, ') =', F8.5)

gives F( 1.5) = 0.12952.

✓ Answer checked step by step Every listed function and its argument type was checked against the FORTRAN IV (and FORTRAN 77 generic) intrinsic function lists; the example was compiled and run with gfortran.

↑ Back to the question list

Write a FORTRAN program to evaluate the following sum: S=∑i=110(−1)nXn/2n(n−1)

1998 · Paper II · Q12c · 20 marks

Solution

Note on the question. The printed sum runs over i=1i=1 to 10 but the terms are in nn, and at n=1n=1 the factor n(n−1)n(n-1) is 0. We take the index to be nn and the ten terms n=2,3,…,11n=2,3,\dots,11: S=∑n=211(−1)nXn/2n(n−1)(X≥0).S=\sum_{n=2}^{11}\frac{(-1)^nX^{n/2}}{n(n-1)}\qquad(X\ge0). (If the intended limits are n=2n=2 to 10, change the DO-loop limit from 11 to 10.)

Points to note.

  • n/2n/2 must be computed in real arithmetic (N/2.0); N/2 would be integer division.
  • n(n−1)n(n-1) is converted to real with FLOAT.
  • (−1)n(-1)^n is obtained as (-1.0)**N (or by switching a sign variable each time).

Program.

C     EVALUATE S = SUM OF (-1)**N * X**(N/2) / (N*(N-1)), N = 2 TO 11
      READ (5,*) X
      S = 0.0
      DO 10 N = 2, 11
         S = S + (-1.0)**N * X**(N/2.0) / FLOAT(N*(N-1))
   10 CONTINUE
      WRITE (6,20) X, S
   20 FORMAT (1X,'X =',F10.4,5X,'S =',F14.6)
      STOP
      END

Sample run. Input 2 gives

 X =    2.0000     S =      0.491971

Alternative without powers in the loop (faster): keep a running term. Since Xn/2=X(n−1)/2⋅XX^{n/2}=X^{(n-1)/2}\cdot\sqrt X, start with T = X (the value of Xn/2X^{n/2} at n=2n=2) and SG = 1.0, and in each pass use S = S + SG*T/FLOAT(N*(N-1)), then update T = T*SQRT(X) and SG = -SG.

✓ Checked by computer We compiled the program with gfortran and ran it: for X = 2 it prints S = 0.491971, which matches a Python evaluation of the same sum.

↑ Back to the question list

What are machine, assembly and high level languages? State their merits and limitations,.

1997 · Paper II · Q12a · 20 marks

Solution

1. Machine language (first generation). Instructions written in binary (0s and 1s) that the processor executes directly; each instruction has an operation code and memory addresses.

  • Merits: executed directly — no translation; fastest execution; full control of the hardware; efficient use of memory.
  • Limitations: machine-dependent (a program for one computer does not run on another); very hard to write, read and debug; the programmer must remember codes and manage memory addresses; error-prone and slow to write.

2. Assembly language (second generation). Uses mnemonics (e.g. LOAD, ADD, STORE, JMP) and symbolic names for addresses instead of binary codes; translated into machine language by an assembler, roughly one machine instruction per statement.

  • Merits: easier to write and understand than machine language; symbolic addresses; still efficient and close to the hardware; useful for system software, device drivers and time-critical routines.
  • Limitations: still machine-dependent; needs knowledge of the hardware; programs are long and tedious; needs an assembler; less productive than high-level languages.

3. High-level languages (third generation and beyond) — FORTRAN, COBOL, BASIC, Pascal, C, and today Python, R, Java. Statements resemble English and mathematical notation (Y = A*X + B); one statement produces many machine instructions; translated by a compiler or interpreter.

  • Merits: machine-independent (portable); easy to learn, write, read and maintain; programmer concentrates on the problem, not the machine; built-in library functions and data structures; easier debugging; much higher productivity.
  • Limitations: need translation (compile time, compiler software); the object code is usually less efficient in speed and memory than hand-written assembly; less direct control of the hardware.

Summary.

Machine Assembly High-level
Form Binary codes Mnemonics English-like statements
Translator None Assembler Compiler/interpreter
Portability None None High
Ease of programming Very hard Hard Easy
Execution efficiency Highest High Lower

✓ Answer checked step by step Every point was checked against the standard classification of programming languages.

↑ Back to the question list

(i) Distinguish between a FUNCTION sub-programme and a SUBROUTINE sub-programme. Also state the rules governing their use. (ii) Explain the uses of ‘Computed GO TO’ and ‘Assigned GO TO’ statements in FORTRAN. Also state the rules governing their use.

1997 · Paper II · Q12b · 20 marks

Solution

(i) FUNCTION and SUBROUTINE sub-programmes.

Point FUNCTION sub-programme SUBROUTINE sub-programme
Purpose Computes and returns a single value through its name Performs a task; can return any number of values (or none) through its arguments or COMMON
First statement REAL FUNCTION F(X,Y) or FUNCTION F(X,Y) SUBROUTINE S(A,B,N)
How called By using its name in an expression: Z = F(A,B) + 1.0 By a CALL statement: CALL S(A,B,N)
Name Has a type (by first letter or type statement) and must be assigned a value inside Name has no value or type
Arguments At least one argument (in FORTRAN IV) May have none

Rules governing their use.

  1. Each is a separate program unit beginning with FUNCTION/SUBROUTINE and ending with END; control returns to the calling program by RETURN.
  2. The actual arguments in the call must agree in number, order and type with the dummy arguments in the definition.
  3. Dummy arguments can be variables, array names (dimensioned inside), or sub-program names (declared EXTERNAL in the caller).
  4. In a FUNCTION, the function name must be assigned a value before RETURN.
  5. A sub-programme cannot call itself (no recursion in FORTRAN IV) and must not redefine a constant passed as an argument.
  6. Variables other than arguments are local; data may also be shared through COMMON blocks.

Example:

      FUNCTION AREA(R)
      AREA = 3.14159 * R * R
      RETURN
      END

      SUBROUTINE STATS(X, N, XM, SD)
      DIMENSION X(N)
      ...
      RETURN
      END

Called as A = AREA(2.0) and CALL STATS(X, 50, XM, SD).

(ii) Computed GO TO and Assigned GO TO.

Computed GO TO — a multi-way branch on the value of an integer variable:

      GO TO (10, 20, 30), K

If K=1K=1 control goes to statement 10, if K=2K=2 to 20, if K=3K=3 to 30.

  • Rules: the index must be an integer variable (an integer expression in FORTRAN 77); the labels must be statement numbers in the same program unit (a label may be repeated); if K<1K<1 or K>K> the number of labels, control passes to the next statement (in FORTRAN IV the result was undefined); a comma precedes the index.
  • Use: choosing among several alternatives, e.g. a menu of options or different formulas by case code.

Assigned GO TO — branch to a label previously stored in an integer variable by an ASSIGN statement:

      ASSIGN 50 TO KR
      ...
      GO TO KR, (40, 50, 60)
  • Rules: the variable must have been given a label by ASSIGN (not by an ordinary assignment KR = 50); while it holds a label it must not be used in arithmetic; the list of possible labels (optional in some compilers) must contain the assigned label; all labels must be in the same program unit.
  • Use: returning from a common block of code to different points (a “local subroutine”), or setting a branch once and using it later.

(Both are obsolete in modern Fortran and are replaced by SELECT CASE and internal procedures.)

✓ Answer checked step by step The FUNCTION/SUBROUTINE example and both GO TO forms were compiled with gfortran (legacy mode) and behaved as described.

↑ Back to the question list

Write a FORTRAN programme to calculate the correlation coefficient on the basis of a set of n pairs of observations (Xi,Yi), i=1,2,…,n, to be read by the programme.

1997 · Paper II · Q12c · 20 marks

Solution

Formula. For nn pairs (Xi,Yi)(X_i,Y_i), r=∑(Xi−X‾)(Yi−Y‾)∑(Xi−X‾)2∑(Yi−Y‾)2.r=\frac{\sum(X_i-\bar X)(Y_i-\bar Y)}{\sqrt{\sum(X_i-\bar X)^2\,\sum(Y_i-\bar Y)^2}} . We compute the means first and then the deviation sums (two passes), which is more accurate than the one-pass “raw sums” formula.

Program.

C     CORRELATION COEFFICIENT FROM N PAIRS (X,Y)
      DIMENSION X(500), Y(500)
      READ (5,*) N
      READ (5,*) (X(I), Y(I), I = 1, N)
C     MEANS
      SX = 0.0
      SY = 0.0
      DO 10 I = 1, N
         SX = SX + X(I)
         SY = SY + Y(I)
   10 CONTINUE
      XB = SX / FLOAT(N)
      YB = SY / FLOAT(N)
C     SUMS OF SQUARES AND PRODUCTS OF DEVIATIONS
      SXX = 0.0
      SYY = 0.0
      SXY = 0.0
      DO 20 I = 1, N
         DX = X(I) - XB
         DY = Y(I) - YB
         SXX = SXX + DX*DX
         SYY = SYY + DY*DY
         SXY = SXY + DX*DY
   20 CONTINUE
      R = SXY / SQRT(SXX*SYY)
      WRITE (6,30) N, R
   30 FORMAT (1X,'N =',I5,5X,'R =',F10.6)
      STOP
      END

Input and output. Data are read in free format: first nn, then the pairs. For the input

5
1 2   2 4   3 5   4 4   5 5

the program prints

 N =    5     R =  0.774597

(Check by hand: X‾=3\bar X=3, Y‾=4\bar Y=4, Sxy=6S_{xy}=6, Sxx=10S_{xx}=10, Syy=6S_{yy}=6; r=6/60=0.7746r=6/\sqrt{60}=0.7746.)

Notes. DIMENSION allows up to 500 pairs (enlarge if needed). If all XX (or all YY) are equal, SxxSyy=0S_{xx}S_{yy}=0 and rr is undefined; a test IF (SXX*SYY .LE. 0.0) can be added to print a message instead.

✓ Checked by computer We compiled the program with gfortran and ran it on the pairs (1, 2), (2, 4), (3, 5), (4, 4), (5, 5): it prints R = 0.774597, which matches numpy’s corrcoef.

↑ Back to the question list

Explain the following control statements in FORTRAN language: (i) Unconditional GO TO (ii) Computed GO TO (iii) Arithmetic IF.

1996 · Paper II · Q12b · 20 marks

Solution

FORTRAN executes statements in sequence; control statements change this order.

(i) Unconditional GO TO.

      GO TO n

Control passes always to the statement labelled nn.

  • Example: GO TO 50 jumps to statement 50.
  • Rules: nn must be the label of an executable statement in the same program unit. The statement after a GO TO must carry a label, or it can never be reached. It is used to form loops (with an IF to exit) and to skip blocks of statements.

(ii) Computed GO TO.

      GO TO (n1, n2, ..., nk), I

Control passes to n1n_1 if I=1I=1, to n2n_2 if I=2I=2, …, to nkn_k if I=kI=k.

  • Example: GO TO (10, 20, 30), MONTH — a three-way branch on the value of MONTH.
  • Rules: II must be an integer variable (FORTRAN IV) with value between 1 and kk; otherwise the result is undefined (FORTRAN 77: falls through to the next statement). The labels must be in the same program unit and may repeat. The comma before II is required.

(iii) Arithmetic IF.

      IF (e) n1, n2, n3

The arithmetic expression ee is evaluated; control passes to n1n_1 if e<0e<0, to n2n_2 if e=0e=0, to n3n_3 if e>0e>0.

  • Example: solving a quadratic, IF (B*B - 4.0*A*C) 10, 20, 30 — complex roots at 10, equal roots at 20, distinct real roots at 30.
  • Rules: ee may be integer or real (not logical or complex); all three labels must be given (two may be equal, giving a two-way branch); they must be executable statements in the same program unit. Because of rounding, testing a real expression for exactly zero is risky.

(Modern Fortran replaces these with block IF … THEN … ELSE, SELECT CASE and DO WHILE.)

✓ Answer checked step by step Each of the three statements was compiled with gfortran (legacy mode) and branched as described.

↑ Back to the question list

Write a FORTRAN program to compute the coefficient of variation from a data set having n ungrouped observations.

1996 · Paper II · Q12c · 20 marks

Solution

Formula. For ungrouped observations X1,…,XnX_1,\dots,X_n, X‾=1n∑Xi,σ=1n∑(Xi−X‾)2,CV=σX‾×100%.\bar X=\frac1n\sum X_i,\qquad \sigma=\sqrt{\frac1n\sum(X_i-\bar X)^2},\qquad CV=\frac{\sigma}{\bar X}\times100\% . (If the sample s.d. with divisor n−1n-1 is wanted, change FLOAT(N) to FLOAT(N-1) in the s.d. line.)

Program.

C     COEFFICIENT OF VARIATION OF N UNGROUPED OBSERVATIONS
      DIMENSION X(1000)
      READ (5,*) N
      READ (5,*) (X(I), I = 1, N)
C     MEAN
      S1 = 0.0
      DO 10 I = 1, N
         S1 = S1 + X(I)
   10 CONTINUE
      XBAR = S1 / FLOAT(N)
C     STANDARD DEVIATION
      S2 = 0.0
      DO 20 I = 1, N
         S2 = S2 + (X(I) - XBAR)**2
   20 CONTINUE
      SD = SQRT(S2 / FLOAT(N))
C     COEFFICIENT OF VARIATION (PER CENT)
      CV = 100.0 * SD / XBAR
      WRITE (6,30) XBAR, SD, CV
   30 FORMAT (1X,'MEAN =',F12.4,3X,'S.D. =',F12.4,3X,'C.V. =',F8.2,' %')
      STOP
      END

Sample run. Input

5
10 12 14 16 18

Output:

 MEAN =     14.0000   S.D. =      2.8284   C.V. =   20.20 %

(Check: X‾=14\bar X=14, σ=40/5=2.828\sigma=\sqrt{40/5}=2.828, CV=20.2%CV=20.2\%.)

Note. The C.V. is meaningful only when X‾>0\bar X>0 (ratio-scale data); a check IF (XBAR .LE. 0.0) can print a warning.

✓ Checked by computer We compiled the program with gfortran and ran it on 10, 12, 14, 16, 18: it prints mean 14, s.d. 2.8284 and C.V. 20.20%, matching Python.

↑ Back to the question list

More on Optimization Techniques

Questions: UPSC Civil Services (Main) Examination, Statistics Paper II, 1996–2026. Solutions: Optional Province. Found an error? Tell us.

Spotted an error? Tell us.

We classify every PYQ with care, but mistakes can slip in. If a question is in the wrong topic, has a typo, the wrong year, or is missing, let us know. We review every report and update the page.

Report an Error
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted