<?xml version="1.0" encoding="UTF-8"?>
<quiz>
<!-- question: 55826  -->
  <question type="coderunner">
    <name>
      <text>Simple C++ question with floating-point tolerance</text>
    </name>
    <questiontext format="html">
      <text><![CDATA[<p>This question demonstrates the use of a per-test-case template grader that checks the output from a C++ program to see if it matches the expected result to within a given absolute tolerance. It is just a simplistic proof of concept. In particular:</p>
<ol>
<li>It assumes the output from the student's program is a single line containing just one floating point number.</li>
<li>It uses a per-test-case grader which results in the student's code being compiled and run separately for each test case. This is very inefficient - a full combinator template grader should really be used, but that adds significant extra complexity.</li>
</ol>
<p>The question posed to the student for demonstration purposes is just the following:</p>
<p>Write a C++ program that reads a single floating point number from stdin and computes its square root using Newton's method to an accuracy of 0.0001. Print your computed result. You may assume the input value is a positive float. </p>]]></text>
    </questiontext>
    <generalfeedback format="html">
      <text></text>
    </generalfeedback>
    <defaultgrade>1</defaultgrade>
    <penalty>0</penalty>
    <hidden>0</hidden>
    <idnumber></idnumber>
    <coderunnertype>python3</coderunnertype>
    <prototypetype>0</prototypetype>
    <allornothing>1</allornothing>
    <penaltyregime>10, 20, ...</penaltyregime>
    <precheck>0</precheck>
    <hidecheck>0</hidecheck>
    <showsource>0</showsource>
    <answerboxlines>18</answerboxlines>
    <answerboxcolumns>100</answerboxcolumns>
    <answerpreload></answerpreload>
    <globalextra></globalextra>
    <useace></useace>
    <resultcolumns></resultcolumns>
    <template><![CDATA[import subprocess, json

TOLERANCE = 0.0001

__student_answer__ = """{{ STUDENT_ANSWER | e('py') }}"""
test = json.loads("""{{TEST | json_encode }}""")

with open("prog.cpp", "w") as outfile:
    outfile.write(__student_answer__)
    
fraction = 0 # Pessimism
abort = False

compile_result = subprocess.run(
    ['g++', 'prog.cpp', '-o', 'prog'],
    capture_output=True,
    text=True,
)

if compile_result.returncode != 0:
    got = f"*** Compile error ***\n{compile_result.stderr}"
    abort=True
else:
    # Compile OK. Try running it.
    result = subprocess.run(['./prog'], capture_output=True, text=True, check=True)
    got = result.stdout
    
    try:
        got_float = float(got)
        expected_float = float(test['expected'])
        if abs(got_float - expected_float) <= TOLERANCE:
            fraction = 1
    except ValueError:
        got = f"Output was '{got.rstrip()}'\nCannot be converted to a float.\n"
        got += "Further testing aborted."
        abort = True
    except Exception as e:
        got = f"Unexpected error: {e}"

result = {"fraction": fraction, "got": got, "abort": abort}
print(json.dumps(result))
]]></template>
    <iscombinatortemplate>0</iscombinatortemplate>
    <allowmultiplestdins></allowmultiplestdins>
    <answer><![CDATA[#include <iostream>
#include <cmath>

#define EPSILON 0.0001
using namespace std;

int main() {
    double n;
    cin >> n; // We'll assume this gives us n > 0.

    // Newton's method for square root.
    double x = n;  // Initial guess.
    double last_x = -10; // Silly value to get things rolling.
    while (abs(last_x - x) > EPSILON) {
        last_x = x;
        x = 0.5 * (x + n / x);
    }
    
    cout << x << endl;
    return 0;
}]]></answer>
    <validateonsave>1</validateonsave>
    <testsplitterre></testsplitterre>
    <language></language>
    <acelang>cpp</acelang>
    <sandbox></sandbox>
    <grader>TemplateGrader</grader>
    <cputimelimitsecs></cputimelimitsecs>
    <memlimitmb></memlimitmb>
    <sandboxparams></sandboxparams>
    <templateparams></templateparams>
    <hoisttemplateparams>1</hoisttemplateparams>
    <extractcodefromjson>1</extractcodefromjson>
    <templateparamslang>None</templateparamslang>
    <templateparamsevalpertry>0</templateparamsevalpertry>
    <templateparamsevald>{}</templateparamsevald>
    <twigall>0</twigall>
    <uiplugin></uiplugin>
    <uiparameters></uiparameters>
    <attachments>0</attachments>
    <attachmentsrequired>0</attachmentsrequired>
    <maxfilesize>10240</maxfilesize>
    <filenamesregex></filenamesregex>
    <filenamesexplain></filenamesexplain>
    <displayfeedback>1</displayfeedback>
    <giveupallowed>0</giveupallowed>
    <prototypeextra></prototypeextra>
    <testcases>
      <testcase testtype="0" useasexample="1" hiderestiffail="0" mark="1.0000000" >
      <testcode>
                <text></text>
      </testcode>
      <stdin>
                <text>4.0</text>
      </stdin>
      <expected>
                <text>2.0</text>
      </expected>
      <extra>
                <text></text>
      </extra>
      <display>
                <text>SHOW</text>
      </display>
    </testcase>
      <testcase testtype="0" useasexample="1" hiderestiffail="0" mark="1.0000000" >
      <testcode>
                <text></text>
      </testcode>
      <stdin>
                <text>100.0</text>
      </stdin>
      <expected>
                <text>10.0</text>
      </expected>
      <extra>
                <text></text>
      </extra>
      <display>
                <text>SHOW</text>
      </display>
    </testcase>
      <testcase testtype="0" useasexample="1" hiderestiffail="0" mark="1.0000000" >
      <testcode>
                <text></text>
      </testcode>
      <stdin>
                <text>2.0</text>
      </stdin>
      <expected>
                <text>1.4142135623730951</text>
      </expected>
      <extra>
                <text></text>
      </extra>
      <display>
                <text>SHOW</text>
      </display>
    </testcase>
      <testcase testtype="0" useasexample="0" hiderestiffail="0" mark="1.0000000" >
      <testcode>
                <text></text>
      </testcode>
      <stdin>
                <text>27</text>
      </stdin>
      <expected>
                <text>5.196152422706632</text>
      </expected>
      <extra>
                <text></text>
      </extra>
      <display>
                <text>SHOW</text>
      </display>
    </testcase>
      <testcase testtype="0" useasexample="0" hiderestiffail="0" mark="1.0000000" >
      <testcode>
                <text></text>
      </testcode>
      <stdin>
                <text>99.98</text>
      </stdin>
      <expected>
                <text>9.998999949995</text>
      </expected>
      <extra>
                <text></text>
      </extra>
      <display>
                <text>SHOW</text>
      </display>
    </testcase>
    </testcases>
  </question>

</quiz>