import matplotlib.pyplot as plt
string = input("Please enter a function: ")
Here the code that I want to convert. I want to convert this to variable to graph the function. Other part of the code will be:
domain = [x for x in range(-10,10)]
range = [string for x in domain]
And I want the string in range be variable in order to Python can run the code. For example if a user enter, let's say,
string = "x ** 2 + x * 2 + 1"
Then I want a method or something that will convert this string to a variable. And in the end I want to get:
string = x ** 2 + x * 2 + 1
By getting this I can get a plot from matplotlib. Finally code will be:
domain = [x for x in range(-10,10)]
range = [x ** 2 + x * 2 + 1 for x in domain]
Thanks in advance!
A quick & dirty approach would be to use the native function eval. For instance define the following high-order function:
def str_to_func(string):
return lambda x: eval(string)
which can be used in this way:
function = str_to_func(string)
values = [function(x) for x in domain]
plt.plot(domain, values)
I got this error when I try to use some numbers on my code, I ask the user to enter the first angle, so python use Newton-raphson to give a new number. But when I enter small numbers o even some random numbers I get that error. Here's my code, this is my first time using python:
import numpy as np
def cos(x):
return np.cos(np.radians(x))
def sin(x):
return np.sin(np.radians(x))
D = 5
Q = 18
def poli(x):
y= (2/D**2)*((((D*(Q**2))/9.81)*(sin(x)))**0.33) + 0.25*sin(2*x) + 0.5*x - x
return (y)
def deri(x):
d=0.0087*cos(2*x) + ((0.0155*(Q**0.66)*cos(x))/(D*9.81*((D*sin(x))/9.81)*0.67)) - 0.5
return (d)
print ("Método de Newton-Raphson")
x = float(input('Introduce el valor de inicio '))
erroru=0.001
raiz=[ ]
raiz.insert(0,0)
i=0
error=1
while abs(error) > erroru:
x1=x-(poli(x)/deri(x))
raiz.append(x1)
i=i+1
x=x1
error=(raiz[i]-raiz[i-1])/raiz[i]
print (x)
I don't know how to fix it
the np.cos and np.sin are referring to radians. no need to convert
import numpy as np
def cos(x):
return np.cos(x)
def sin(x):
return np.sin(x)
D = 5
Q = 18
def poli(x):
y= (2/D**2)*((((D*(Q**2))/9.81)*(sin(x)))**0.33) + 0.25*sin(2*x) + 0.5*x - x
return (y)
def deri(x):
d=0.0087*cos(2*x) + ((0.0155*(Q**0.66)*cos(x))/(D*9.81*((D*sin(x))/9.81)*0.67)) - 0.5
return (d)
print ("Método de Newton-Raphson")
x = float(input('Introduce el valor de inicio '))
erroru=0.001
raiz=[ ]
raiz.insert(0,0)
i=0
error=1
while abs(error) > erroru:
x1=x-(poli(x)/deri(x))
raiz.append(x1)
i=i+1
x=x1
error=(raiz[i]-raiz[i-1])/raiz[i]
print (x)
The problem is that you have numpy.float64 type in your code and the float64 are like c float, and overload all operations (including) power to work as such.
You error occurs when you do
(value ** 0.33)
where value is a negative numpy.float64 type.
Value ** 0.33 is probably an imaginary number. Python numpy float64s are real, so the above is an invalid expression (python float can handle that).
To make it work you could cast that to float(but the final result could be incorrect)
You can convert your poli function as such:
def poli(x):
y= (2/D**2)*(float(((D*(Q**2))/9.81)*(sin(x)))**0.33) + 0.25*sin(2*x) + 0.5*x - x
return (y)
After that you get another error, but that is another story
TypeError: ufunc 'radians' not supported for the input types, and the
inputs could not be safely coerced to any supported types according to
the casting rule ''safe''
I am running a watershell ptraj file on a coordinate file to find distances of salt ions to a specific atom. I have made the watershell command and I am attempting to write a python code that can run the watershell for a range of values. the command is as follows:
for xi in range(0, 25, 0.2):
x = xi
y = xi + 0.2
file = 'file1'+str(xi)+'.dat'
command = 'watershell :141-182#C1 output.dat lower xi upper y :183-392#Na+'
print(x,y)
I am getting TypeError: 'float' object cannot be interpreted as integer.
The range function won't take a float as a step value; instead you have to use an int. You can get around this by using a multiplier and then dividing when you need to make use of your variable, try something like this:
for xi in range(0, 250, 2):
x = round(xi / 10.0,1)
y = round(xi / 10.0,1) + 0.2
file = 'file1'+str(xi)+'.dat'
command = 'watershell :141-182#C1 output.dat lower xi upper y :183-392#Na+'
print(x,y)
The expression range(0, 25, 0.2) is illegal. The step has to be an integer, so 0.2 is not allowed. I guess you'll have to use a for loop.
I'm taking a Python course at Udacity, and I'm trying to work this out for myself without looking at the answer. Perhaps you can give me a hint for my logic?
Below are the instructions and what I have so far. We haven't learned conditional statements yet, so I can't use those. We've only learned how to assign/print a variable, strings, indexing strings, sub-sequences, and .find. They just introduced the str command in this final exercise.
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
x = 3.54159
#ENTER CODE BELOW HERE
x = str(x)
dec = x.find('.')
tenth = dec + 1
print x[0:dec]
////
So this gets me to print the characters up to the decimal point, but I can't figure out how to have the computer check whether "tenth" is > 4 or < 5 and print out something according to the answer.
I figured I could probably get far enough for it to return a -1 if "tenth" wasn't > 4, but I don't know how I can get it to print x[0:dec] if it's < 5 and x[0:dec]+1 if it's > 4.
:/
Could someone please give me a nudge in the right direction?
This is a weird restriction, but you could do this:
x = str(x)
dec_index = x.find('.')
tenth_index = dec_index + 1
tenth_place = x[tenth_index] # will be a string of length 1
should_round_up = 5 + tenth_place.find('5') + tenth_place.find('6') + tenth_place.find('7') + tenth_place.find('8') + tenth_place.find('9')
print int(x[0:dec_index]) + should_round_up
What we do is look at the tenths place. Since .find() returns -1 if the argument isn't found, the sum of the .find() calls will be -4 if if the tenths place is 5, 6, 7, 8, or 9 (since one of the .find() calls will succeed and return 0), but will be -5 if the tenths place is 0, 1, 2, 3, or 4. We add 5 to that, so that should_round_up equals 1 if we should round up, and 0 otherwise. Add that to the whole number part, and we're done.
That said, if you weren't subject to this artificial restriction, you would do:
print round(x)
And move on with your life.
judging by the accepted answer you only expects floats so that is pretty trivial to solve:
x = 3.54159
# split on .
a, b = str(x).split(".")
# cast left side to int and add result of test for right side being greater or equal to 5
print(int(a) + (int(b) >= 5))
(int(b) > 5) will be either 1 or 0 i.e True/False so we either add 1 when right side is > .5 or flooring when it's < .5 and adding 0.
If you were doing it mathematically you just need to print(int(x+.5)), anything >= .5 will mean x will be rounded up and floored when it is < .5.
x = 3.54159
# split on .
a, b = str(x).split(".")
# cast left side to int and add result of test for right side being greater or equal to 5
print(int(a) + (int(b[0]) >= 5))
# above code will not work with 3.14567 and the number with having two or more digits after decimal
I think it's easier...
x = x + 0.5
intPart, decPart = str(x).split(".")
print intPart
Examples:
If x = 1, then it will become 1.5 and intPart will be 1.
If x = 1.1, then it will become 1.6 and intPart will be 1.
If x = 1.6, then it will become 2.1 and intPart will be 2.
Note: it will only work for positive numbers.
This code will round numbers to the nearest whole
without using conditionals
You can do it this way
x = 3.54159
x = x + 0.5 # This automatically takes care of the rounding
str_x = str(x) # Converting number x to string
dp = str_x.find('.') # Finding decimal point index
print str_x[:dp] # Printing upto but excluding decimal point
I did the same course at Udacity. solved it using the following code:
y = str(x)
decimal = y.find('.')
y_increment = y[decimal+1:]
print decimal
print y_increment
# Section below finds >5
check5 = y_increment.find('5',0,1)
check6 = y_increment.find('6',0,1)
check7 = y_increment.find('7',0,1)
check8 = y_increment.find('8',0,1)
check9 = y_increment.find('9',0,1)
yes_increment = (check5 + 1) + (check6 + 1) + (check7 + 1) + (check8 + 1) + (check9 + 1)
print check5, check6, check7, check8, check9
#Calculate rounding up
z = x + (yes_increment)
z = str(z)
final_decimal = z.find('.')
print z[:final_decimal]
I am trying to convert hex value to float using (Python 2.7) the following method:
def hex2float(x):
y = 0
z = x.decode('hex')
try:
y = struct.unpack('!f', z)[0]
except:
print sys.exc_info()[1]
print 'z = ' + z
print 'y = %s' % (y)
print 'x = ' + x
return
def foo28():
x = '615885' #8.9398e-039
hex2float(x)
The output is as follows:
unpack requires a string argument of length 4
z = aXà
y = 0
x = 615885
I notice that I get the exception message for really small values. Is there a proper way to convert hex values to floating values for such cases.
You need four bytes to unpack, so prepend null bytes if necessary:
z = x.decode('hex')
z = '\0' * (4 - len(z)) + z
Normally str.decode only outputs as much bytes as necessary to represent the value, so that's why you only see it happen for small values.
This works perfectly:
>>> z = '615885'.decode("hex")
>>> z = '\0' * (4 - len(z)) + z
>>> struct.unpack('!f', z)
(8.939797951825212e-39,)
If you're going to do doubles as well this solution still works, just change 4 to 8.