How to resolve the algorithm Convert decimal number to rational step by step in the Tcl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Convert decimal number to rational step by step in the Tcl programming language

Table of Contents

Problem Statement

The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: Acceptable output: Finite decimals are of course no problem:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Convert decimal number to rational step by step in the Tcl programming language

Source code in the tcl programming language

#!/usr/bin/env tclsh

 proc dbl2frac {dbl {eps 0.000001}} {
   for {set den 1} {$den<1024} {incr den} {
      set num [expr {round($dbl*$den)}]
      if {abs(double($num)/$den - $dbl) < $eps} break
   }
   list $num $den
 }
#-------------------- That's all... the rest is the test suite
if {[file tail $argv0] eq [file tail [info script]]} {
    foreach {test            -> expected} {
	{dbl2frac 0.518518}  -> {42 81}
	{dbl2frac 0.75}      -> {3 4}
	{dbl2frac 0.9054054} -> {67 74}
    } {
	catch $test res
	if {$res ne $expected} {
	    puts "$test -> $res, expected $expected"
	}
    }
}


  

You may also check:How to resolve the algorithm Hello world/Standard error step by step in the Racket programming language
You may also check:How to resolve the algorithm Non-decimal radices/Output step by step in the Klingphix programming language
You may also check:How to resolve the algorithm Amicable pairs step by step in the AWK programming language
You may also check:How to resolve the algorithm Count in factors step by step in the Ring programming language
You may also check:How to resolve the algorithm Arithmetic derivative step by step in the RPL programming language