Hi,

just some programs to calculate the periode of a mathematical pendulum. It is calculated using the equation

T0=2πlgT_0 = 2 \pi \cdot \sqrt{\frac{l}{g}}

I included also always two checks:

  1. the input is a number and
  2. the input is bigger than 0.

JavaScript

<script type="text/javascript">
function MyError(message){
    this.message = message;
}

function get_positive_number(name){
    var theForm = document.forms["pendulum"];
    var val_name = theForm.elements[name].value;
    var val_name_num = Number(val_name);
    if (val_name == "" || val_name_num == NaN){
        throw new MyError(name.concat(" is not a number!"));
    }
    if (val_name_num<=0){
        throw new MyError(name.concat(" is not positive!"));
    }
    return val_name_num;
}

function calculateTime(){
    var res_div = document.getElementById('result');
    try {
        var g = get_positive_number('g');
        var l = get_positive_number('l');
    } catch (ex){
        if (ex instanceof MyError){
            res_div.innerHTML = ex.message;
            return;
        } else {
            throw ex;
        }
    }
    var t = 2 * Math.PI * Math.sqrt(l/g);
    res_div.innerHTML = 'Pendulum time (s): ' + t;
}

</script>

<form action="" id="pendulum" onsubmit="return false;">
    <fieldset>
        <legend>Calculate the pendulum time!</legend>
        <p><label for="g" >Gravitational constant g (m/s^2): </label><input type="number" min=0 name="g" id="g" value=9.81 step="any"/></p>
        <p><label for="l" >Pendulum length l (cm): </label><input type="number" min=0 name="l" id="l" step="any"/></p>
        <p><input type='submit' id='submit' value='Calculate' onclick="calculateTime()" /></p>
        <p><div id="result"></div></p>
    </fieldset>
</form>

Live demo:

Calculate the pendulum time!

Python3

# -*- coding: utf-8 -*-
import math
if __name__ == "__main__":
    g = 9.81
    while True:
        user_input = input("Please type pendulum length in cm: ")
        try:
            pendulum_length = float(user_input)
        except ValueError:
            print("You typed not a number")
        if not pendulum_length > 0:
            print("The given number is smaller or equal to 0")
        else:
            break
    pendulum_time = 2 * math.pi * math.sqrt(pendulum_length / (100 * g))
    print("The time is ", pendulum_time, "s")

C++

#define _USE_MATH_DEFINES
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
#include <limits>

using namespace std;

template<typename T>
int getTypefromCIN(T &s){
    string input;
    getline(cin, input);
    stringstream tmpstream(input);
    if (tmpstream >> s){
        return 0;
    }
    return 1;
}


int main (){
    double length, g=9.81, time;
    const double scale = M_PI * 2;
    while (true){
        cout << "Please, type the pendulum length in cm: ";
        if(!getTypefromCIN(length)){
            if(length > 0){
                break;
            }else{
                cout << "Pendulum length must be positive!" << endl;
                continue;
            }
        }
        cout << "Input was not a number! " << endl;
    }
    double factor = sqrt(length/g);
    time = scale * factor;
    if(!isfinite(time)){
        cout << "Overflow during math operation" << endl;
        return 1;
    }else{
        cout << "Pendulum time in s: " << time << endl;
        return 0;
    }
}

D

import std.stdio;
import std.math;

void main(){
    real pendel_length;
    char[] trash;
    while(1){
        writeln("Please type pendulum length in cm: ");
        try {
            readf(" %s", &pendel_length);
            if(pendel_length > 0){
                break;
            }else{
                writeln("The number is smaller or equal to 0");
            }
        } catch (Exception exc) {
            writeln("You typed not a number");
            readln();
        }
    }
    static real g = 9.81;
    real pendulum_time = 2 * PI * sqrt(pendel_length / 100 / g);
    writeln("The time is ", pendulum_time, "s");
}

Fortran

program pendulum
    implicit none
    REAL :: pendulum_length = 0, g = 9.81, PI, pendulum_time
    PI = 4.D0*DATAN(1.D0)
    do while( pendulum_length == 0 )
        500 write(*,*) "Please, write the pendulum length in cm! "
        pendulum_length = 0
        READ(*,"(F40.0)", ERR=500) pendulum_length
        if(pendulum_length <= 0) then
            pendulum_length = 0
            write(*,*) "The number was smaller then 0! "
        end if
    end do
    pendulum_time = 2 * PI * SQRT(pendulum_length / 100 / g)
    write(*, *) "The time is ", pendulum_time, "s"
end program

Ada

---gnatmake -gnato -fstack-check -gnatE pendulum.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.IO_Exceptions;
    procedure pendulum is
        pendulum_length : FLOAT := 0.0;
        pendulum_time : FLOAT;
        g : CONSTANT FLOAT := 9.81;
        package FLOAT_Functions is new Ada.Numerics.Generic_Elementary_Functions(Standard.FLOAT);
    begin
        while pendulum_length = 0.0 loop
            Put("Please input the pendulums length in cm: ");
            begin
                Ada.Float_Text_IO.Get(pendulum_length);
                if pendulum_length <= 0.0 then
                    Put("Number was smaller or equal 0");
                    pendulum_length := 0.0;
                end if;
            exception
                when ADA.IO_EXCEPTIONS.DATA_ERROR =>
                    Put ("Not a number");
                    New_Line;
                    pendulum_length := 0.0;
                    Skip_Line;
            end;
        end loop;
        pendulum_time := 2.0 * Ada.Numerics.Pi * FLOAT_Functions.Sqrt(pendulum_length / 100.0 / g);
        Put("The time is ");
        Put(pendulum_time);
        Put("s");
    end pendulum;

Rust

use std::io;

fn main() {
    let g = 9.81_f64;
    let pendulum_length;
    loop {
        let mut user_input = String::new();
        println!("Please type pendulum length in cm: ");
        io::stdin()
            .read_line(&mut user_input)
            .expect("failed to read from stdin");
        let trimmed = user_input.trim();
        match trimmed.parse::<f64>() {
            Ok(i) => {
                if i > 0_f64 {
                    pendulum_length = i;
                    break;
                }else{
                    println!("The given number is smaller or equal to 0.");
                }
            },
            Err(..) => println!("Input was not recognized as a number.")
        }
    }
    let t = 2_f64 * std::f64::consts::PI * (pendulum_length / (100_f64 * g)).sqrt();
    println!("The time is {} s", t);
}

Haskell

import Text.Read
readpendulumlength :: IO Float
readpendulumlength = do
    putStrLn "Please, write the pendulum length in cm: "
    line <- getLine
    let f = readMaybe line :: Maybe Float
    case f of
        Just f -> if (f>0) then
            return f
        else do
            putStrLn "Pendulum length must be positive!"
            readpendulumlength
        Nothing -> readpendulumlength

mathpendulumtime :: Float -> Float -> Float
mathpendulumtime g l = 2 * pi * sqrt (l/g)

main = do
       pendulum_length <-  readpendulumlength
       putStrLn "Pendulum time in s: "
       print(mathpendulumtime (9.81 * 100) pendulum_length)

C#/Mono

using System;

public class PendulumTime
{
    static public void Main ()
    {
        double pendulum_length;
        while (true){
                Console.WriteLine("Please, write the pendulum length in cm: ");
                try{
                        /// be careful! this reads the double with cultural
                        /// differences i.e. 5.00 becomes 500 on a German pc while
                        /// a American pc would see 5.00
                        pendulum_length = Convert.ToDouble(Console.ReadLine());
                }
                catch (System.FormatException){
                        continue;
                }
                if (pendulum_length > 0){
                        break;
                }
                Console.WriteLine("The pendulum length needs to be positive!");
        }
        double pendulum_time = 2 * Math.PI * Math.Sqrt(pendulum_length / (9.81 * 100));
        Console.WriteLine("Pendulum time in s: ");
        Console.WriteLine(pendulum_time);
    }
}

Kotlin

import java.lang.Math.PI
import java.lang.Math.sqrt
val g = 9.81

fun main(args: Array<String>){
    var l: Double?
    while(true){
        println("Please give pendulum length in cm:")
        l = try { readLine()!!.toDouble() } catch (e: NumberFormatException) { null }
        if (l == null){
            println("Input was not a float!")
            continue
        }
        if (l <= 0){
            println("Pendulum length must be positive!")
            continue
        }
        break
    }
    println("Pendulum time in s:")
    println(2*PI* sqrt(l!!/g))
}

Scala

import java.lang.Math.sqrt
import java.lang.Math.PI

object main {
  val g=9.81
  var l: Option[Double] = None
  def main(args: Array[String]): Unit = {
    while(l.isEmpty) {
      println("Please give pendulum length in cm:")
      l = try {
        Some(scala.io.StdIn.readDouble())
      } catch {
        case e: NumberFormatException => None
      }
      l match {
        case Some(i) => if(i<=0){println("Pendulum length must be positive!"); l=None}
        case None => println("Input was not a number!")
      }
    }
    println("Pendulum time in s:")
    println(2*PI* sqrt(l.get/g))
  }
}

Published

Category

snippets

Tags