Python Forum
math.sqrt / pow() rounding small floats, workaround?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
math.sqrt / pow() rounding small floats, workaround?
#6
Thanks! Got 4 new Python3 IDE’s. The first one I tried out seems to work fine.

However, this may be the apps fault but the box code you gifted me seems to have a minor bug.
The middle right side border is shifted left, only a space or two from the contents. This is supposedly Py3 btw.

Output:
╔═════════════╗ ║ Hello World ║ ╚═════════════╝
Actually, looks fine when I preview it here LOL. I’ll just try this on my computer :).

Thanks for the help, info and code! If you get bored, feel free to make any improvements or other suggestions to the code I posted. I tried to keep things simple but definitely wouldn’t mind seeing a more efficient/advanced method, pun intended.

Well... On my computer now, emailed the code to myself and pasted into IDLE Python 3.7.

When executed, my def mainMenu(): function is called, but seems to ALWAYS return a value that is unexpected. For example, if I enter '0' my code executes the 'else' block, indicating '0' was not returned. Same for any input that should result in a valid choice. I will likely have time to investigate this later today, but if anybody has any ideas, I'll include an exact copy of my code below. This new version just includes minor changes to the code I originally posted, like the class Gribouillis provided and I commented out a few print functions I had for troubleshooting.

A quick overview of what my code should do:
While loop will Call mainMenu() # This displays a menu with choices 0, 1, 2, 3, 4, 5, 6
Prompt for input and save this to choice
If choice == 1 || 2 || 3 || 4 || 5 || 6, it will return choice
Else, it will return 999
If the returned value is == 1 || 2 || 3 || 4 || 5 || 6, the corresponding branch executes, function is called
Else, prompt to enter a VALID choice is displayed, continue

Again, when I run this, Else always executes. Any help is appreciated!

from __future__ import (absolute_import, division,

                        print_function, unicode_literals)

# ^^ this given by Gribouillis(Python forums)


import math

import decimal # << necessary? will have to determine later on.. 



# class given by Gribouillis(Python forums)

class B:

    h, v, ul, ur, ll, lr = [chr(0x2550 + x) for x in (0, 1, 4, 7, 10, 13)]

     

def boxed(s, indent=0):

    def boxed(s, indent):

        size = len(s) + 2

        t = ' ' * indent if indent else ''

        yield "{}{}{}{}\n".format(t, B.ul, B.h * size, B.ur)

        yield "{}{} {} {}\n".format(t, B.v, s, B.v)

        yield "{}{}{}{}".format(t, B.ll, B.h * size, B.lr)

    return ''.join(boxed(s, indent))

 

print(boxed('Hello World', indent=0))

# end of class, thanks Gribouillis.





def solvePhase():

    xOfL = "N/A"

    xOfC = "N/A"

    r = "N/A"

    print("If you don't have R, Xl, Xc, enter 0 to acquire these before continuing. Otherwise, enter 1.")

    haveValues = input()

    if haveValues == 0:

        print("Enter 0 if Inductor NOT present, 1 if present")

        needXl = input()

        if needXl == 1:

            xOfL = lReact(1)

        print("Enter 0 if Capacitor NOT present, 1 if present")

        needXc = input()

        if needXc == 1:

            xOfC = cReact(1)

        print(xOfL)

        print(xOfC)

    r = input("Enter Resistance in Ohms: ")

    if haveValues == 1:

        xOfL = float(input("Enter Xl in Ohms: "))

        xOfC = float(input("Enter Xc in Ohms: "))

    

    if r == "N/A":

        print("Setting R to 1")

        r = 1

    if xOfL == "N/A":

        print("Setting Xl to 1")

        xOfL = 1

    if xOfC == "N/A":

        print("Setting Xc to 1")

        xOfC = 1

    prePhase = math.atan(((xOfL - xOfC) / r))

    phase = math.degrees(prePhase)

    return "Phase: " + str(phase)

    



def lReact(called):

    fHz = input("Enter Frequency in Hz: ")

    lH = input("Enter inductance in H: ")

    fHz = float(fHz)

    lH = float(lH)

    result = (2.0 * math.pi) * fHz * lH

    if called == 1:

        return result

    message = "Inductive Reactance: "

    completeResult = message + str(result)

    return completeResult + " Ohms Z"

    

def cReact(called):

    fHz = input("Enter Frequency in Hz: ")

    cF = input("Enter capacitance in F: ")

    fHz = float(fHz)

    cF = float(cF)

    

    if cF == 0:

        print("Setting cF to 0.0000000001")

        cF = 0.0000000001

    

    result = 1.0 / ((2.0 * math.pi) * fHz * cF)

    if called == 1:

        return result

    message = "Capacitive Reactance: "

    completeResult = message + str(result)

    return completeResult + " Ohms Z"

    



def seriesZ():

    print("If you don't have R, Xl, Xc, enter 0 to acquire these before continuing. Otherwise, enter 1.")

    solveZ = input()

    if solveZ == 0:

        xOfL = lReact()

        xOfC = cReact()

        print(xOfL)

        print(xOfC)

    r = input("Enter Resistance in Ohms: ")

    xl = input("Enter Xl in Ohms: ")

    xc = input("Enter Xc in Ohms: ")

    r = float(r)

    xl = float(xl)

    xc = float(xc)

    result = math.sqrt((r ** 2) + (((xl-xc)**2)))

    message = "Series Impedance: "

    completeResult = message + str(result)

    return completeResult + " Ohms Z"

         

# reciprocal of the sqrt of the reciprocal of the resistance squared plus the difference of the reciprocal of inductive reactance and the reciprocal of capacitive reactance squared.. 

def parallelZ():

# Setting variables to N/A to check

# whether to include in final calc

# If user does not enter value for

# any, N/A will remain in variable

    xOfL = "N/A"

    xOfC = "N/A"

    r = "N/A"

    

# If reactances NOT known, call method

# with argument(1) to return only 

# the reactance (without message)

# Then assign returned value to

# the reactance variable

    print("If you don't have R, Xl, Xc, enter 0 to acquire these before continuing. Otherwise, enter 1.")

    haveValues = input()

    if haveValues == 0:

        print("Enter 0 if Inductor NOT present, 1 if present")

        needXl = input()

        if needXl == 1:

            xOfL = lReact(1)

        print("Enter 0 if Capacitor NOT present, 1 if present")

        needXc = input()

        if needXc == 1:

            xOfC = cReact(1)



# Always asks if R present

    print("Enter 0 if R NOT present, 1 if present")

    needR = input()

    if needR == 1:

        r = float(input("Enter Resistance in Ohms: "))



# If user has reactances, this 

# branch will execute, skipping

# method calls to calculate each

# reactance value

    if haveValues == 1:

        print("Enter 0 if Inductor NOT present, 1 if present")

        needXl = input()

        if needXl == 1:

            xOfL = float(input("Enter Xl in Ohms: "))

        print("Enter 0 if Capacitor NOT present, 1 if present")

        needXc = input()

        if needXc == 1:

            xOfC = float(input("Enter Xc in Ohms: "))

    

    includeR = 1

    includeXOfL = 1

    includeXOfC = 1

    if r == "N/A":

        print("Omitting R")

        includeR = 0

    if xOfL == "N/A":

        print("Omitting Xl")

        includeXOfL = 0

    if xOfC == "N/A":

        print("Omitting Xc")

        includeXOfC = 0

    

    

    print("Xl: " + str(xOfL))

    print("Xc: " + str(xOfC))

    print("R: " + str(r))

    

        

    if includeR == 1:

        rZ = (r **2)**-1

    if includeXOfL == 1:

        xlZ = (xOfL)**-1

    if includeXOfC == 1:

        xcZ = (xOfC)**-1

    print("rZ: " + str(rZ))

    print("xlZ: " + str(xlZ))

    print("xcZ: " + str(xcZ))



    if includeR == 1 and includeXOfL == 1 and includeXOfC == 1:

        xlcZ = float((xlZ - xcZ)**2)

        prePreResult = float((rZ + xlcZ))

#         print("xlcZ: " + str(xlcZ))

#         print("prePreResult: " + str(prePreResult))

        preResult = (prePreResult)**(1/2)

#         print("preResult: " + str(preResult))

        result = ((preResult)**-1)

        

        message = "Parallel Impedance: "

        completeResult = message + str(result)

        return completeResult

    



def parallelResistance():

    resistor1 = input("Enter 1st resistance: ")

    resistor1 = float(resistor1)

    resistor2 = input("Enter 2nd resistance: ")

    resistor2 = float(resistor2)

    r1 = resistor1

    r2 = resistor2

    result = (1.0 / r1) + (1.0 / r2)

    result = 1.0 / result

    return result



def mainMenu():

    print("*************************")

    print("Enter 0 to Quit")

    print("Enter 1 for || Resistance")

    print("Enter 2 for xC")

    print("Enter 3 for xL")

    print("Enter 4 for Z")

    print("Enter 5 for || Z")

    print("Enter 6 for Phase")

    print("*************************")

    choice = input()

    if choice == 0:

        return choice

    if choice == 1:

        return choice

    if choice == 2:

        return choice

    if choice == 3:

        return choice

    if choice == 4:

        return choice

    if choice == 5:

        return choice

    if choice == 6:

        return choice

    

    return 999



# Main Code #

programIsTerminated = 0

while programIsTerminated == 0:

    menuChoice = mainMenu()

    

    #print(boxed('', indent=0))

    

    if menuChoice == 0:

        #print("====================")

        print("Program Terminated")

        #print("====================")

        # programIsTerminated = 1

        break

    if menuChoice == 1:

        print("====================")

        print("Solving || Resistance")

        print("====================")

        print(parallelResistance())

        continue

    if menuChoice == 2:

        print("====================")

        print("Solving Xc")

        print("====================")

        print(cReact())

        continue

    if menuChoice == 3:

        print("====================")

        print("Solving Xl")

        print("====================")

        print(lReact())

        continue

    if menuChoice == 4:

        print("====================")

        print("Solving Z")

        print("====================")

        print(seriesZ())

        continue

    if menuChoice == 5:

        print("====================")

        print("Solving || Z")

        print("====================")

        print(parallelZ())

        continue

    if menuChoice == 6:

        print("====================")

        print("Solving Phase")

        print("====================")

        print(solvePhase())

        continue

    else:

        print("====================")

        print("Please enter a VALID choice.")

        print("====================")

        continue

        

# print("Program Terminated")
Reply


Messages In This Thread
RE: math.sqrt / pow() rounding small floats, workaround? - by robertHTompkins - Dec-22-2018, 07:27 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 858 Nov-12-2023, 11:53 AM
Last Post: PyDan
  need help rounding joseph202020 7 1,431 Feb-21-2023, 08:13 PM
Last Post: joseph202020
  from numpy array to csv - rounding SchroedingersLion 6 2,379 Nov-14-2022, 09:09 PM
Last Post: deanhystad
  math.log versus math.log10 stevendaprano 10 2,588 May-23-2022, 08:59 PM
Last Post: jefsummers
  floats 2 decimals rwahdan 3 1,703 Dec-19-2021, 10:30 PM
Last Post: snippsat
  Random data generation sum to 1 by rounding juniorcoder 9 3,618 Oct-20-2021, 03:36 PM
Last Post: deanhystad
  Rounding issue kmll 1 1,473 Oct-08-2021, 10:35 AM
Last Post: Yoriz
  Not rounding to desired decimal places? pprod 2 2,631 Mar-05-2021, 11:11 AM
Last Post: pprod
  Why getting ValueError : Math domain error in trig. function, math.asin() ? jahuja73 3 3,895 Feb-24-2021, 05:09 PM
Last Post: bowlofred
  Decimal Rounding error project_science 4 2,849 Jan-06-2021, 03:14 PM
Last Post: project_science

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020