📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / Programmieren-Tutorium / Tutorium-06 / Camera.java
132938 viewsLicense: OTHER
/**1* This class represents a digital camera with an autofocus feature.2*3* @author Markus Iser, Martin Thoma4*5*/6public class Camera {7/** This epsilon is used for internal float comparisons. */8private static final double EPSILON = 1E-6;910/** The objective that is currently used by the camera. */11private final Objective objective;1213/**14* The constructor for objective.15*16* @param objective17* an objective18*/19public Camera(final Objective objective) {20this.objective = objective;21}2223/**24* Check two doubles for equality.25*26* @param fp1 first floating point number27* @param fp2 second floating point number28* @return {@code true} if both floats are equal, otherwise {@code false}29*/30private boolean fpEquals(final double fp1, final double fp2) {31return Math.abs(fp1 - fp2) < EPSILON;32}3334/**35* Determine if the contrast on the left is higher than on the current36* position.37*38* @param objective the objective you are manipulating39* @return {@code true} the contrast on the left of the current position is40* higher, otherwise {@code false}41*/42private boolean isLeftContrastHigher(Objective objective) {43double contrast = objective.getContrast();44objective.stepLeft();45double contrastNew = objective.getContrast();46objective.stepRight();4748// check if the contrast - according to our EPSILON - is the same49if (fpEquals(contrast, contrastNew)) {50return false;51}5253return contrastNew > contrast;54}5556/**57* Adjust objective to get the optimum focus. The optimum focus is58* determined by the highest contrast.59*/60public void autofocus() {61boolean stepLeft;62double contrast = objective.getContrast();6364// determine direction65stepLeft = isLeftContrastHigher(objective);6667// loop until optimum passed68while (objective.getContrast() > contrast69&& !fpEquals(contrast, objective.getContrast())) {70contrast = objective.getContrast();71if (stepLeft) {72objective.stepLeft();73} else {74objective.stepRight();75}76}7778// optional correction-move back79if (!fpEquals(contrast, objective.getContrast())) {80if (stepLeft) {81objective.stepRight();82} else {83objective.stepLeft();84}85}86}87}88899091