How to Print only 4 decimal places in python?
Question:
I am writing a simple program to verify the formula of derivate and in output I am getting too many decimal places which look awful.
I am pretty new to python. I want to only show four decimal places.
here is my code,
from math import *
x = -pi
h = 0.001
while x <= pi:
print("d/dx sin(x) = sin(x+h) - sin(x) / h :", (sin(x + h) - sin(x)) / h)
print("d/dx sin(x) = cos(x): ", cos(x))
x += h
Answers:
You should use string formatting while printing like this
from math import *
x = -pi
h = 0.001
while x <= pi:
print("d/dx sin(x) = sin(x+h) - sin(x) / h :", "{:.4f}".format((sin(x + h) - sin(x)) / h))
print("d/dx sin(x) = cos(x): ", "{:.4f}".format(cos(x)))
x += h
Another way to accomplish the desired output. Note, the rounded value will be of type str
:
from math import *
x = -pi
h = 0.001
while x <= pi:
print("d/dx sin(x) = sin(x+h) - sin(x) / h :", "%.4f" % ((sin(x + h) - sin(x)) / h))
print("d/dx sin(x) = cos(x): ", "%.4f" % cos(x))
x += h
use f-string and .4f like this:
print(f"{0.123456789:.4f}")
I am writing a simple program to verify the formula of derivate and in output I am getting too many decimal places which look awful.
I am pretty new to python. I want to only show four decimal places.
here is my code,
from math import *
x = -pi
h = 0.001
while x <= pi:
print("d/dx sin(x) = sin(x+h) - sin(x) / h :", (sin(x + h) - sin(x)) / h)
print("d/dx sin(x) = cos(x): ", cos(x))
x += h
You should use string formatting while printing like this
from math import *
x = -pi
h = 0.001
while x <= pi:
print("d/dx sin(x) = sin(x+h) - sin(x) / h :", "{:.4f}".format((sin(x + h) - sin(x)) / h))
print("d/dx sin(x) = cos(x): ", "{:.4f}".format(cos(x)))
x += h
Another way to accomplish the desired output. Note, the rounded value will be of type str
:
from math import *
x = -pi
h = 0.001
while x <= pi:
print("d/dx sin(x) = sin(x+h) - sin(x) / h :", "%.4f" % ((sin(x + h) - sin(x)) / h))
print("d/dx sin(x) = cos(x): ", "%.4f" % cos(x))
x += h
use f-string and .4f like this:
print(f"{0.123456789:.4f}")