# Trial - Conversion Rounding / Distance Maths # Purpose: Test the convert_distance() logic BEFORE connecting it to the GUI. # This is the standalone trial of the conversion maths component. # # The approach: convert everything to metres first (base unit), # then convert from metres to the target unit. # This means only ONE formula is needed per unit, not one per unit PAIR. # Conversion factors: how many metres is one of each unit? TO_METERS = { "km": 1000, "m": 1, "cm": 0.01, "mm": 0.001 } def convert_distance(value, from_unit, to_unit): """ Converts a distance value from one unit to another. Uses metres as an intermediate base unit. """ # Step 1: convert the input value to metres in_metres = value * TO_METERS[from_unit] # Step 2: convert metres to the target unit result = in_metres / TO_METERS[to_unit] # Step 3: round to 4 decimal places, strip trailing zeros rounded = round(result, 4) if rounded == int(rounded): return int(rounded) return rounded # ===== Test runs ===== print("===== Expected value tests =====") tests = [ (1, "km", "m", 1000), (1000, "m", "km", 1), (1, "m", "cm", 100), (100, "cm", "m", 1), (1, "cm", "mm", 10), (10, "mm", "cm", 1), (1, "km", "cm", 100000), (1, "km", "mm", 1000000), (2.5, "km", "m", 2500), (500, "m", "mm", 500000), ] all_passed = True for value, from_unit, to_unit, expected in tests: result = convert_distance(value, from_unit, to_unit) status = "PASS" if result == expected else "FAIL" if status == "FAIL": all_passed = False print(f" {status}: {value} {from_unit} -> {to_unit} = {result} (expected {expected})") print() if all_passed: print("All tests passed!") else: print("Some tests FAILED - check logic above.") print() print("===== Decimal / boundary tests =====") decimal_tests = [ (0, "km", "m"), (0.001,"km", "m"), (1.5, "m", "cm"), (999, "mm", "m"), ] for value, from_unit, to_unit in decimal_tests: result = convert_distance(value, from_unit, to_unit) print(f" {value} {from_unit} -> {to_unit} = {result}")