简体   繁体   English

如何将用户输入的常量 (pi,e) 转换为 python 中的浮点数?

[英]How convert user inputted constant (pi,e) to float in python?

I'm writing a code which must compute definite integral of a function. I'll provide code in the below.我正在编写一个代码,它必须计算 function 的定积分。我将在下面提供代码。 How can I urge computer to understand user input "pi" or "e" for constant numbers?我怎样才能促使计算机理解用户输入的常数“pi”“e” Problem is that I must convert the type of input to float , for following calculations.问题是我必须输入类型转换为float ,以便进行后续计算。 So when user inputs pi it's raising ValueError .因此,当用户输入pi时,它会引发ValueError How can we get constants like pi to give bounds?我们怎样才能得到像pi这样的常量来给出界限?

from  sympy import *
from sympy.abc import *
import math
import numpy as np
import time
import sys
import pandas as pd

############                                                     ############

#######      Calculating Definite Integral of a given function using trapezium method      #######


#########                                                   ##############     



cuts = 100 #is number of cuts

########################## DataFrame object of aveliable differantiable functions

all_functions = {"Trigonometric": ["sin", "cos",'tan','cot','sec','csec','sinc'],
                    "Trigonometric Inverses": ["asin", "acos",'atan','acot','asec','acsec'," "],
                    'Hyperbolic Functions': [ 'sinh', 'cosh', 'tanh', 'coth'," "," "," "],
                    'Hyperbolic Inverses':['asinh','acosh','atanh','acoth','asech','acsch'," "],
                    "Exponential": ["exp", 'log','ln',"log(base,x)", ' ', " "," "],
                    "Roots":["root","sqrt",'cbrt',' '," "," "," "],
                    "Powers": ["x**n (n is all real numbers)"," "," "," "," "," "," "],
                    "Combinatorical": ['factorial'," "," "," "," "," "," "]}
df = pd.DataFrame(all_functions,index = [" "," "," "," "," "," "," "])
df.columns.name = "Funcion'c classes"
df.index.name = "Functions"
df = df.T 
###############################################



#####Defining functions which will compute integral using trapezium method

##### Trapezium method fomrula -- Integral(f(x),a,b) = (a-b)/n * ( (y_0+y_n)/2 + y_1+y_2+...+ y_(n-1) )

def integral():
    print("Enter Function to integrate: ", end=" ") 
    function = sympify(input()) #converting string input to sympy expression
    print("Enter lower bound: ", end = " ")
    lower = float(input()) #lower bound of definite integral
    print("Enter upper bound: ", end = " ")
    upper = float(input()) # upper bound of definite integral

    xi = np.linspace(lower,upper,cuts+1) #cutting X axis to n+1 parts, for x0=a<x1<x2<...xi<x(i+1)<...<xn=b

    ####### y_i = function(x_i) ########inserting "x"s in function and computing y values, for using trapezium method formula
    ylist = [] 
    for i in range(len(xi)):
        ys = function.subs(x,xi[i]) 
        ylist.append(ys)


    sum2 = 0 #second part of trapezium method sum
    for j in range(1,cuts):
        sum2 = sum2 + ylist[j]
    sum1 = (ylist[0]+ylist[cuts])/2 #first part of trapezium method sum
    result = (upper-lower)*(sum1+sum2)/cuts  #result of an integral
    ####computing error of an integral 
    derivative = diff(function,x,2) #2nd differential of function at given point 
    derresult = derivative.subs(x,(lower-upper)/2) #result of derivative of 
    error = abs((upper-lower)**3*derresult/(12*cuts**12)) #error of definite integral 

    dots = "Integrating....\n"
####typing ^^^ this line alternatly 
    for l in dots:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(0.045)

    equals = "================\n\n"
 ####typing ^^^ this line alternatly    
    for l in equals:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(0.045)

    #raise this error when bounds give infinity result
    if result == math.inf or result == -math.inf:
        print("Bounds are false")
    else:
        ###printing integral result
            print("Derfinite integral of " + str(function) +" from " +str(lower)+" to "+ str(upper)+" = "+ "%.5f +- %e" %(result, error)+"\n")

            ######## typing equlas alternatly
            for l in equals:
                sys.stdout.write(l)
                sys.stdout.flush()
                time.sleep(0.055)




try:   ### Trye integral() function if errors are occuring execute excepts
    integral()

except TypeError:   ##execute this when TypeError occured , i.e. function typed incorrectly
    print("The Function You have entered does not exist or is not differentiable or consists other symbol ranther then \'x\' !\nTo see list of all differentiable functions please type \"Functions\" \n")
    function_input = input()
    function_list = ["Functions", "Function","functions",'function',"FUNCTIONS",'FUNCTIONS']

    if function_input  in function_list:   #if user input is correct print out DataFrame of aveliable functions, and excecute integral()
        print(df, end = "\n\n")
        integral()

    else:  #if user input is incorrect return statement below, which will wait to user input print out function's list and excecute integral()
        print("Please Type \'Functions\' correctly")
        function_input = input()
        print(df, end = "\n\n")
        integral()
except SympifyError:
    print("\nExpression You have entered is not a fully written function or not not written correctly.\n")
    integral()
except ValueError:
    print("\nBounds must be numbers.\n")
    integral()

You can write a function that recognizes certain names before calling float() to parse it normally.您可以在调用float()之前编写一个识别某些名称的函数以正常解析它。

def my_float(s):
    constants = {"pi": 3.14159, "e": 2.71928}
    if s in constants:
        return constants[s]
    else:
        return float(s)

Then you can read write:然后你可以读写:

print("Enter lower bound: ", end = " ")
lower = my_float(input()) #lower bound of definite integral

you can use this code:您可以使用此代码:

from numpy import pi,e

value = eval(input())  # if you entered "pi", value will be = 3.14

print(value)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从用户输入的float中删除一组字符 - Python - How to remove a set of characters from a user inputted float - Python 如何在 python 中将 E 表示法字符串转换为具有固定指数的浮点数 - How to convert a E notation string to a float with fixed exponent in python 如何将值转换为用户输入的类型? - How to convert value to user-inputted type? 如何计算用户输入的浮点数(包括0)的小数位? - How to count decimal places of a user-inputted float INCLUDING 0? 如何添加用户在 Python 中输入的一组数字? - How to add a set of numbers that the user inputted in Python? 如何在Python中处理用户输入的对数方程 - How to deal with user inputted logarithmic equations in Python Python:计算pi时“long int太大而不能转换为float” - Python: “long int too large to convert to float” when calculating pi 如何将用户输入的(字符串)函数转换为数学模块 - How to convert user inputted (string) function into a math module 如何在 Python 中将“2.6840000e+01”类型的数据转换为浮点数? - How to convert '2.6840000e+01' type like datas to float in Python? 如何使用python中的变量值转换输入的数据 - How to convert the inputted data using the variable values in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM