Skip to content

Instantly share code, notes, and snippets.

@AFAgarap
Last active May 16, 2016 16:44
Show Gist options
  • Save AFAgarap/7b51f0315cc9c15932aa6207c20297cc to your computer and use it in GitHub Desktop.
Save AFAgarap/7b51f0315cc9c15932aa6207c20297cc to your computer and use it in GitHub Desktop.
Computation for error analysis
# Numerical Analysis, Summer Semester A.Y. 2015-2016, Adamson University
# Author: A.F. Agarap
# Error Analysis
import os
def main():
true_value = float(eval(input("Enter true value: ")))
approximate_value = float(eval(input("Enter approximate value: ")))
float_range = int(input("Enter number of precision values: "))
chop_approximate_value = truncate(approximate_value, float_range)
chop_error = get_error(true_value, chop_approximate_value)
chop_relative_error = get_relative_error(true_value, chop_approximate_value)
round_approximate_value = round_val(approximate_value, float_range)
round_error = get_error(true_value, round_approximate_value)
round_relative_error = get_relative_error(true_value, round_approximate_value)
print("Chop()\n\tError: {}".format(chop_error),"\n","\b\tRelative Error: {}%".format(chop_relative_error))
print("\nRound()\n\tError: {}".format(round_error),"\n","\b\tRelative Error: {}%".format(round_relative_error))
# Author: David Z, A.F. Agarap
# Link: http://goo.gl/DTdDEt
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return float('.'.join([i, (d+'0'*n)[:n]]))
def round_val(f, n):
return float('{0:.{1}f}'.format(f, n))
def get_error(true_value, approximate_value):
return (abs(true_value - approximate_value))
def get_relative_error(true_value, approximate_value):
return (abs(true_value - approximate_value) / abs(true_value))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment