在python中如何将用户输入的常量(pi,e)转换为浮点?
我正在写一个代码,它必须计算函数的定积分。我将在下面提供代码。我怎样才能促使计算机理解用户输入的常量的“pi”或“e”?问题是,我必须将输入类型转换为float,以便进行以下计算。因此,当用户输入pi时,它会引发值错误。我们怎样才能得到像pi这样的常数来给出边界在python中如何将用户输入的常量(pi,e)转换为浮点?,python,constants,user-input,sympy,pi,Python,Constants,User Input,Sympy,Pi,我正在写一个代码,它必须计算函数的定积分。我将在下面提供代码。我怎样才能促使计算机理解用户输入的常量的“pi”或“e”?问题是,我必须将输入类型转换为float,以便进行以下计算。因此,当用户输入pi时,它会引发值错误。我们怎样才能得到像pi这样的常数来给出边界 from sympy import * from sympy.abc import * import math import numpy as np import time import sys import pandas as pd
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()
来自sympy导入的*
从sympy.abc导入*
输入数学
将numpy作为np导入
导入时间
导入系统
作为pd进口熊猫
############ ############
#######用梯形法计算给定函数的定积分#######
######### ##############
切割=100#是切割的数量
##########################可微函数的DataFrame对象
所有函数={“三角”:[“sin”,“cos”,“tan”,“cot”,“sec”,“csec”,“sinc'],
“三角反演”:[“asin”、“acos”、“atan”、“acot”、“asec”、“acsec”、“acsec”],
‘双曲函数’:[‘sinh’、‘cosh’、‘tanh’、‘coth’、“”、“”、“”、“”、“”、“”],
‘双曲线逆’:[‘asinh’、‘acosh’、‘atanh’、‘acoth’、‘asech’、‘acsch’、“”],
“指数”:[“exp”、“log”、“ln”、“log(base,x)”、“”、“”、“”],
“根”:[“根”,“sqrt”,“cbrt”,“根”,“根”,“sqrt”,“根],
“幂”:[“x**n(n都是实数)”,,,,,,,,,,,,,,,],
“组合”:['factorial'、“”、“”、“”、“”、“”、“”、“”、“”]}
df=pd.DataFrame(所有函数,索引=[“”,“”,“”,“”,“”,“”,“”,“”])
df.columns.name=“function'c classes”
df.index.name=“函数”
df=df.T
###############################################
#####定义使用梯形法计算积分的函数
#####梯形法公式——积分(f(x),a,b)=(a-b)/n*((y_0+y_n)/2+y_1+y_2+…+y_(n-1))
def integral():
打印(“输入要集成的函数:”,end=“”)
function=sympify(input())#将字符串输入转换为sympy表达式
打印(“输入下限:”,end=“”)
lower=浮点(input())#定积分的下界
打印(“输入上限:”,end=“”)
上限=浮点(输入())#定积分的上限
席=NP.LimStudio(下,上,割+ 1)x切割x轴到n+1个部分,对于x0= a,您可以编写一个函数,在调用<代码>浮点()/<代码>之前,先识别某些名称,以解析它。
def my_float(s):
constants = {"pi": 3.14159, "e": 2.71928}
if s in constants:
return constants[s]
else:
return float(s)
然后你可以读写:
print("Enter lower bound: ", end = " ")
lower = my_float(input()) #lower bound of definite integral