6. Recurring Decimals๏ƒ

Recurring decimals ae limited here to denominators of 3, 6, 7, 9, 11.
This limits the number of possible recurring decimals to a total of 26.
The worksheet can have up to 26 recurring decimal questions.

6.1. Sample recurring decimals worksheets๏ƒ

recdec_1_q

recdec_1_ans

recdec_2_q

recdec_2_ans


6.2. Latex templates๏ƒ

The LaTeX recurring decimals question template is below.
 1\documentclass[leqno, 12pt]{article}
 2\usepackage[a4paper, portrait, margin=2cm]{geometry}
 3\usepackage{amsmath}
 4\usepackage{multicol}
 5\usepackage{dcolumn}
 6    
 7\newcolumntype{d}[1]{D{.}{.}{#1}}
 8\usepackage{multicol}
 9\usepackage{fancyhdr}
10
11
12\def \HeadingQuestions {\section*{\Large Name: \underline{\hspace{8cm}} \hfill Date: \underline{\hspace{3cm}}} \vspace{-3mm}
13{Recurring decimals: Questions} \vspace{1pt}\hrule}
14
15% raise footer with page number
16\fancypagestyle{myfancypagestyle}{
17  \fancyhf{} % clear all header and footer fields
18  \renewcommand{\headrulewidth}{0pt} % no rule under header
19  \fancyfoot[C] {\thepage} \setlength{\footskip}{16pt} % raise page number 6pt
20}
21\pagestyle{myfancypagestyle}  % apply myfancypagestyle
22
23% 
24\begin{document}
25    \HeadingQuestions
26    \vspace{-5mm}
27    \begin{multicols}{3}
28        <<cols>>
29    \end{multicols}
30\end{document}
The LaTeX recurring decimals answer template is below.
 1\documentclass[leqno, 12pt]{article}
 2\usepackage[a4paper, portrait, margin=2cm]{geometry}
 3\usepackage{amsmath}
 4\usepackage{multicol}
 5\usepackage{dcolumn}
 6    
 7\newcolumntype{d}[1]{D{.}{.}{#1}}
 8\usepackage{multicol}
 9\usepackage{fancyhdr}
10
11
12\def \HeadingAnswers {\section*{\Large Name: \underline{\hspace{8cm}} \hfill Date: \underline{\hspace{3cm}}} \vspace{-3mm}
13{Recurring decimals: Answers} \vspace{1pt}\hrule}
14
15% raise footer with page number
16\fancypagestyle{myfancypagestyle}{
17  \fancyhf{} % clear all header and footer fields
18  \renewcommand{\headrulewidth}{0pt} % no rule under header
19  \fancyfoot[C] {\thepage} \setlength{\footskip}{16pt} % raise page number 6pt
20}
21\pagestyle{myfancypagestyle}  % apply myfancypagestyle
22
23% 
24\begin{document}
25    \HeadingAnswers
26    \vspace{-5mm}
27    \begin{multicols}{3}
28        <<cols>>
29    \end{multicols}
30\end{document}
The diagram template is below.
1\begin{flalign} 
2    &\frac{<<numerator>>}{<<denominator>>} =\quad&
3\end{flalign}
The diagram answer template is below.
1\begin{flalign} 
2    &\frac{<<numerator>>}{<<denominator>>} = <<nonrepeating>> \overline {<<repeating>>}&
3\end{flalign}

6.3. Decimals python๏ƒ

The python below requires the 4 .tex files listed above.
The 2 custom python modules required are:
  1"""
  2Module of functions to return decimals dictionary for LaTeX
  3"""
  4import random
  5
  6
  7# from fractions import Fraction
  8# from decimal import Decimal, getcontext
  9
 10
 11def get_num_denom_pairs_list(shuffle_bool=True):
 12    """list of possible rec dec fractions (nominator, denomiator)"""
 13    num_denom_pairs_list = [
 14        (1, 3),
 15        (2, 3),
 16        (1, 6),
 17        (5, 6),
 18        (1, 7),
 19        (2, 7),
 20        (3, 7),
 21        (4, 7),
 22        (5, 7),
 23        (6, 7),
 24        (1, 9),
 25        (2, 9),
 26        (4, 9),
 27        (5, 9),
 28        (7, 9),
 29        (8, 9),
 30        (1, 11),
 31        (2, 11),
 32        (3, 11),
 33        (4, 11),
 34        (5, 11),
 35        (6, 11),
 36        (7, 11),
 37        (8, 11),
 38        (9, 11),
 39        (10, 11),
 40    ]
 41    if shuffle_bool:
 42        random.shuffle(num_denom_pairs_list)
 43    return num_denom_pairs_list
 44
 45
 46def repeating_dec_sol(numerator, denominator):
 47    """returns rec dec like 2.1(6) with the 6 recurring"""
 48    negative = False
 49    if denominator == 0:
 50        return "Undefined"
 51    if numerator == 0:
 52        return "0"
 53    if numerator * denominator < 0:
 54        negative = True
 55    if numerator % denominator == 0:
 56        return str(numerator / denominator)
 57
 58    num = abs(numerator)
 59    den = abs(denominator)
 60
 61    output = ""
 62    output += str(num // den)
 63    output += "."
 64
 65    quotient_num = []
 66    while num:
 67        # In case the remainder is equal to zero, there are no repeating
 68        # decimals. Therefore, we don't need to add any parenthesis and we can
 69        # break the while loop and return the output.
 70        remainder = num % den
 71        if remainder == 0:
 72            for i in quotient_num:
 73                output += str(i[-1])
 74            break
 75        num = remainder * 10
 76        quotient = num // den
 77
 78        # If the new numerator and quotient are not already in the list, we
 79        # append them to the list.
 80        if [num, quotient] not in quotient_num:
 81            quotient_num.append([num, quotient])
 82        # If the new numerator and quotient are instead already in the list, we
 83        # break the execution and we prepare to return the final output.
 84        # We take track of the index position, in order to add the parenthesis
 85        # at the output in the right place.
 86        elif [num, quotient] in quotient_num:
 87            index = quotient_num.index([num, quotient])
 88            for i in quotient_num[:index]:
 89                output += str(i[-1])
 90            output += "("
 91            for i in quotient_num[index:]:
 92                output += str(i[-1])
 93            output += ")"
 94            break
 95    if negative:
 96        output = "-" + output
 97    return output
 98
 99
100def get_rec_dec_parts(recdec):
101    # delete trainligng )
102    recdec = recdec[:-1]
103    split_string_list = recdec.split("(")
104    return split_string_list[0], split_string_list[1]
105
106
107def rec_dec_dict(numerator, denominator):
108    # $$\frac{<<num>>}{<<denom>>} =<<nonrepeating>> \overline {<<repeating>>}$$
109    recdec = repeating_dec_sol(numerator, denominator)
110    nonrepeating, repeating = get_rec_dec_parts(recdec)
111    #
112    kv = dict()
113    kv["numerator"] = f"{numerator}"
114    kv["denominator"] = f"{denominator}"
115    kv["nonrepeating"] = f"{nonrepeating}"
116    kv["repeating"] = f"{repeating}"
117    return kv
118
119
120# if __name__ == "__main__":
121#     print("starting")
122#     print(get_num_denom_pairs_list())
123#     print("finished")
124# print(repeating_dec_sol(452,495), 913/999)
125
The Python to create worksheets of questions involving recurring decimals, is below.
  1from pathlib import Path
  2import subprocess
  3import time
  4import recurring_decimals_functions as recdecf
  5
  6
  7currfile_dir = Path(__file__).parent
  8tex_template_path = currfile_dir / "recurring_decimals_worksheet_template.tex"
  9texans_template_path = currfile_dir / "recurring_decimals_worksheet_ans_template.tex"
 10tex_diagram_template_path = (
 11    currfile_dir / "recurring_decimals_worksheet_diagram_template.tex"
 12)
 13tex_diagram_ans_template_path = (
 14    currfile_dir / "recurring_decimals_worksheet_diagram_ans_template.tex"
 15)
 16
 17
 18def convert_to_pdf(tex_path, currfile_dir, aux_path):
 19    """
 20    Converts a TeX file to PDF format using pdfLaTeX.
 21
 22    Args:
 23        tex_path (str): The path to the TeX file.
 24        currfile_dir (str): The path to the directory where the TeX file is located.
 25        aux_path (str): The path to the directory where auxiliary files will be stored.
 26
 27    Returns:
 28        subprocess.CompletedProcess: A subprocess.CompletedProcess object containing information about the completed process.
 29
 30    Raises:
 31        FileNotFoundError: If the TeX file does not exist.
 32        subprocess.CalledProcessError: If pdfLaTeX returns a non-zero exit code.
 33    """
 34    result = subprocess.run(
 35        [
 36            "pdfLaTeX",
 37            tex_path,
 38            "-output-directory",
 39            currfile_dir,
 40            "-aux-directory",
 41            aux_path,
 42        ],
 43        stdout=subprocess.PIPE,
 44    )
 45
 46
 47# tex_keys = ["numerator", "denominator", "nonrepeating", "repeating"]
 48tex_keys_q = ["numerator", "denominator"]
 49
 50
 51def make1_diagram(tex_diagram_template_txt, tex_diagram_template_txt_ans, num, denom):
 52    posttext = r"\vspace{12pt}"
 53    kv = recdecf.rec_dec_dict(num, denom)
 54
 55    for key, value in kv.items():
 56        tex_diagram_template_txt_ans = tex_diagram_template_txt_ans.replace(
 57            "<<" + key + ">>", value
 58        )
 59
 60    for key, value in kv.items():
 61        if key in tex_keys_q:
 62            tex_diagram_template_txt = tex_diagram_template_txt.replace(
 63                "<<" + key + ">>", value
 64            )
 65        else:
 66            tex_diagram_template_txt = tex_diagram_template_txt.replace(
 67                "<<" + key + ">>", ""
 68            )
 69
 70    # return tex_diagram_template_txt
 71    return tex_diagram_template_txt + posttext, tex_diagram_template_txt_ans + posttext
 72
 73
 74def main():
 75    #
 76    numq = input("Enter the number of questions from 1 to 26 \n")
 77    if numq.strip().isdigit():
 78        numq = int(numq)
 79        if not numq in range(1, 27):
 80            numq = 26  # 16 by default
 81    else:
 82        numq = 26  # 16 by default
 83    #
 84    #
 85    shuffle_bool = input("Enter T of F to shuffle the order \n").capitalize()
 86    if shuffle_bool == "T":
 87        shuffle_bool = True
 88    else:
 89        shuffle_bool = False
 90    #
 91    filename = input("Enter the base filename to be added to the prefix recdec_: \n")
 92    if not filename:
 93        filename = "1"  # "recdec_1_q and recdec_1_ans as default file"
 94    # set names of files that are made
 95    # questions
 96    tex_output_path = currfile_dir / f"recdec_{filename}_q.tex"
 97    aux_path = currfile_dir / "temp"
 98    # answers
 99    tex_output_path_ans = currfile_dir / f"recdec_{filename}_ans.tex"
100
101    # Read in the LaTeX template file
102    with open(tex_template_path, "r") as infile:
103        tex_template_txt = infile.read()
104    # Read in the LaTeX template file for answers
105    with open(texans_template_path, "r") as infile:
106        tex_template_txt_ans = infile.read()
107    # Read in the LaTeX diagram template file
108    with open(tex_diagram_template_path, "r") as infile:
109        tex_diagram_template_txt = infile.read()
110    with open(tex_diagram_ans_template_path, "r") as infile:
111        tex_diagram_template_txt_ans = infile.read()
112
113    num_denom_pairs_list = recdecf.get_num_denom_pairs_list(shuffle_bool)
114    
115    # <<cols>>
116    # generate column text and column text for answers
117    col1_text = ""
118    col1_text_ans = ""
119    rmax = numq + 1
120    for i in range(1, rmax):
121        num, denom = num_denom_pairs_list[i-1]
122        img_tex, img_tex_ans = make1_diagram(tex_diagram_template_txt, tex_diagram_template_txt_ans, num, denom)
123        col1_text += img_tex
124        col1_text_ans += img_tex_ans
125
126    # Replace the <<cols>> placeholder in the LaTeX template with the generated diagrams
127    tex_template_txt = tex_template_txt.replace("<<cols>>", col1_text)
128    tex_template_txt_ans = tex_template_txt_ans.replace("<<cols>>", col1_text_ans)
129
130    # Write the question tex to an output file
131    with open(tex_output_path, "w") as outfile:
132        outfile.write(tex_template_txt)
133
134    # Write the answer tex to an output file
135    with open(tex_output_path_ans, "w") as outfile:
136        outfile.write(tex_template_txt_ans)
137
138    # Wait for the file to be created
139    time.sleep(1)
140    # Convert the LaTeX files to PDFs
141    convert_to_pdf(tex_output_path, currfile_dir, aux_path)
142    convert_to_pdf(tex_output_path_ans, currfile_dir, aux_path)
143
144
145if __name__ == "__main__":
146    print("starting")
147    main()
148    print("finished")