Home > Enterprise >  Python round() to remove trailing zeros
Python round() to remove trailing zeros

Time:12-22

The code below is used to find the x* using Gradient Descent and the problem here is that the final result of req8 is -1.00053169969469 and when I round it, it results in -1.00000000000000.

How can I round to get -1.0 or -1.00 instead, without using any other module?

from sympy import * 
import numpy as np 

global x, y, z, t 
x, y, z, t = symbols("x, y, z, t") 

def req8(f, eta, xi, tol): 
    dx = diff(f(x), x)
    arrs = [xi]
    for i in range(100):
        x_star = arrs[-1] - eta * round(dx.subs(x, arrs[-1]), 7)
        if abs(dx.subs(x, x_star)) < tol:
            break
        arrs.append(x_star)
    print(arrs[-1])
    print(round(arrs[-1], 2))

def f_22(x):
    return x**2   2*x - 1
req8(f_22, 0.1, -5, 1e-3)

CodePudding user response:

Use the format function to print your rounded result with the desired number of digits (2, in the example below):

print("{:.2f}".format(round(arrs[-1], 2)))

EDIT: as pointed out by @SultanOrazbayev, rounding is no longer necessary here and you may print your result using the following expression:

print("{:.2f}".format(arrs[-1]))

  • Related