I want to draw a function which has periodic condition.
My code is as following.
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
import itertools
from itertools import *
r = np.linspace(-1, 1, 1000)
f(r) = np.exp(-pow(r,2)/5)
In this situation, the period of f(r) equals 2. I want to plot (r,f(r)) in the range -inf < r < 1.
With using itertools.repeat, how can I plot that figure?
f(r) = np.exp(-pow(r,2)/5) isn't valid python. Just try print np.exp(-pow(r, 2)/5). Or def f(r): return np.exp(-pow(r, 2)/5)
from numpy import * does nothing for below it.
from itertools import * does nothing below for below it.
Imports are in the form of:
import blah
blah.blah_function()
or
from blah import blah_function
blah_function()
or (don't do this... ever... please)
from blah import *
blah_function()
also
float('inf'), -float('inf'), and float('-inf') are all valid in python.
Related
I want to change the color of the line but I have no idea how I should code.
import numpy as np
from sympy import *
import sympy as sp
t=sp.symbols('t')
y=sp.Function('y')
overdamped = Eq(10*y(t).diff(t,2)+100*y(t).diff(t,1)+90*y(t),0)
psol1=dsolve(overdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
underdamped = Eq(10*y(t).diff(t,2)+10*y(t).diff(t,1)+90*y(t),0)
psol3=dsolve(underdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
plot(psol1.rhs, psol3.rhs, (t,0,10))
This is the work I've done. The plot works well but I want the two lines to be in differnt colors. I'll be very thankful if you help me out.
import numpy as np
from sympy import *
import sympy as sp
t=sp.symbols('t')
y=sp.Function('y')
overdamped = Eq(10*y(t).diff(t,2)+100*y(t).diff(t,1)+90*y(t),0)
psol1=dsolve(overdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
underdamped = Eq(10*y(t).diff(t,2)+10*y(t).diff(t,1)+90*y(t),0)
psol3=dsolve(underdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
p = plot(psol1.rhs, psol3.rhs, (t,0,10))
p[0].line_color = 'g'
p[1].line_color = 'r'
p.show()
So i made this code to create a plot that should look like this[This image was done in Mathematica] 1 but for some reason nothing shows up on the plot plot i made.does it have to something with the gam(x_2) or gam itself because i tried defining that as a range but still nothing. please teach me. From the plot made in matematica it seems like he set both the x and y ranges all the way up to 10,000.
import matplotlib.pyplot as plt
import numpy as np
import math
import pylab
%matplotlib inline
gam0 = 72.8
temp = 293.15
def gam(x_2):
return gam0 - 0.0187 * temp * math.log10(1+628.14*55.556*x_2)
x = range(0, 10000)
x_2= x
plt.plot('gam(x_2), x_2')
plt.xlabel('Log_10x_2')
plt.ylabel('gamma (erg cm^2)')
A few fixes needed; defining your function, there's an indent missing, also multiplying the whole array with ' * ' isn't working, so you can save up the values in a separate array through a for loop:
EDIT: Oh, and also while plotting, you don't put the variable names as strings, you just call them as they are.
import matplotlib.pyplot as plt
import numpy as np
import math
import pylab
%matplotlib inline
gam0 = 72.8
temp = 293.15
x = range(0, 10000)
x_2= x
def gam(x_2):
returns = []
for x_i in x_2:
returns.append(gam0 - 0.0187 * temp * math.log10(1+628.14*55.556*x_i))
return returns
plt.plot(gam(x_2), x_2)
plt.xlabel('Log_10x_2')
plt.ylabel('gamma (erg cm^2)')
plt.show()
Indent your function
def gam(x_2):
return gam0 - 0.0187 * temp * math.log10(1+628.14*55.556*x_2)
Find gam(x_2) for each item(x_2) in list x
gam_x = [gam(x_2) for x_2 in x]
Finally, plot and show.
plt.plot(gam_x, x)
plt.xlabel('Log_10x_2')
plt.ylabel('gamma (erg cm^2)')
plt.show()
I am trying to plot with dots hoping in the end i can get a probability density function simulation. My code is:
import random
import math
from numpy import *
from matplotlib.pyplot import *
import matplotlib.pyplot as pl
clock_offset=3000
y=0
p=0.50
for i in range (40):
x = random.random()
if x < p:
clock_offset+=1
for 'bo' in (clock_offset,y):
y+=1
pl.plot(clock_offset,y,'bo')
pl.axis([2980, 3040, 0, 40])
y=0
else:
clock_offset-=1
for 'bo' in (clock_offset,y):
y+=1
pl.plot(clock_offset,y,'bo')
pl.axis([2980, 3040, 0, 40])
y=0
The problem is i can't write a for loop that makes y+=1, when that place (clock_offset,y) has already been occupied with a dot. Any solutions?
I'm not sure what this code of yours is supposed to do. But take a look at this answer of mine that explains how to get a random number on a distribution. Bellow I gave you a rewrite of that C++ code into python.
import random
import math
import numpy as np
import matplotlib.pyplot as plt
def GausPDF(x, a=1., b=2., c=3.):
return a*math.exp( -((x-b)*(x-b)/(2*c*c) ))
def random_on_PDF(PDF, top, bottom, maxPDF):
x = (top-bottom)*np.random.random()+bottom
y = maxPDF*random.random()
while(y>PDF(x)):
x = (top-bottom)*np.random.random()+bottom
y = maxPDF*random.random()
return x,y
x, y, = list(), list()
for i in range(0, 1000):
a,b = random_on_PDF(GausPDF, 10., -5., 1.)
x.append(a)
y.append(b)
plt.scatter(x,y)
plt.show()
Using this code and THIS matplotlib example directly, you can simulate how random voting affects/builds a PDF.
Is that what you're after?
When I call random.sample(arr,length) an error returns random_sample() takes at most 1 positional argument (2 given).I've tried importing numpy under a different name, which doesn't fix the problem.Any thoughts? Thanks
import numpy.random
import random
import numpy as np
from numpy import *
points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]
def cluster(X,center):
clusters = {}
for x in X:
z= min([(i[0], np.linalg.norm(x-center[i[0]])) for i in enumerate(center)], key=lambda t:t[1])
try:
clusters[z].append(x)
except KeyError:
clusters[z]=[x]
return clusters
def update(oldcenter,clusters):
d=[]
r=[]
newcenter=[]
for k in clusters:
if k[0]==0:
d.append(clusters[(k[0],k[1])])
else:
r.append(clusters[(k[0],k[1])])
c=np.mean(d, axis=0)
u=np.mean(r,axis=0)
newcenter.append(c)
newcenter.append(u)
return newcenter
def shouldStop(oldcenter,center, iterations):
MAX_ITERATIONS=0
if iterations > MAX_ITERATIONS: return True
u=np.array_equal(center,oldcenter)
return u
def init_board(N):
X = np.array([(random.uniform(1,4), random.uniform(1, 4)) for i in range(4)])
return X
def kmeans(X,k):
clusters={}
iterations = 0
oldcenter=([[],[]])
center = random.sample(X,k)
while not shouldStop(oldcenter, center, iterations):
# Save old centroids for convergence test. Book keeping.
oldcenter=center
iterations += 1
clusters=cluster(X,center)
center=update(oldcenter,clusters)
return (center,clusters)
X=init_board(4)
(center,clusters)=kmeans(X,2)
print "center:",center
#print "clusters:", clusters
When you use from numpy import * you import all items that are in the numpy namespace into your scripts namespace. When you do this any functions/variables/etc that have the same name will be overwritten by the items from the numpy namespace.
numpy has a subpackage called numpy.random which then overwrote your random import as the code below shows:
import random
# Here random is the Python stdlib random package.
from numpy import *
# As numpy has a random package, numpy.random,
# random is now the numpy.random package as it has been overwritten.
In this case you should instead use import numpy as np which will allow you to access both:
import random
# random now contains the stdlib random package
import numpy as np
# np.random now contains the numpy.random package
Your points is List type, so you should convert it to an array
points = np.asarray(point)
Also, you should use import random
I need to solve an integral equation by python 3.2 in win7.
I want to find an initial guess solution first and then use "fsolve()" to solve it in python.
This is the code:
import numpy as np
from scipy.optimize.minpack import fsolve
from cmath import cos, exp
from scipy.integrate.quadpack import quad
def integrand2(x, b):
return exp(-x)/b
def intergralFunc2(b):
integral,err = quad(integrand2, 0, 10, args=(b)) // **error here**
return 0.01 - integral
import matplotlib.pyplot as plt
def findGuess():
vfunc = np.vectorize(intergralFunc2)
f = np.linspace(-20, 20,10)
plt.plot(f, vfunc(f))
plt.xlabel('guess value')
plt.show()
def solveFunction():
y= fsolve(intergralFunc2, 10)
return y
if __name__ == '__main__':
findGuess()
solution = solveFunction()
print("solution is ", solution)
I got error:
quadpack.error: Supplied function does not return a valid float.
Any help would be appreciated.
Just made the following change and it should work (it worked for me).
remove:
from cmath import exp, cos
include:
from numpy import exp, cos
as explained in the comments, the cmath functions accept only float inputs, not arrays.