{"text": "X = [0, 20, 40, 60, 80, 100]\nY = [26.0, 48.6, 61.6, 71.2, 74.8, 75.2]\n\nn = len(X)-1 # Degree of polynomial = number of points - 1\n\nprint(\"X =\", X)\nprint(\"Y =\", Y, end='\\n\\n')\n\nxp = float(input(\"Find Y for X = \"))\n\n\n# For degree of polynomial 3, number of points n+1 = 4:\n# L[1] = (x-x2)/(x1-x2) * (x-x3)/(x1-x3) * (x-x4)/(x1-x4)\n# L[2] = (x-x1)/(x2-x1) * (x-x3)/(x2-x3) * (x-x4)/(x2-x4)\n# L[3] = (x-x1)/(x3-x1) * (x-x2)/(x3-x2) * (x-x4)/(x3-x4)\n# L[4] = (x-x1)/(x4-x1) * (x-x2)/(x4-x2) * (x-x3)/(x4-x3)\n\n# L[i] *= (x-xj)/(xi-xj) where i, j = 1 to n+1 and j != i\n# y += Y[i]*L[i] where i = 1 to n+1\n # List index 0 to n\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~ Method 1: Using for loop ~~~~~~~~~~~~~~~~~~~~~~~~\n\nyp = 0 # Initial summation value\nfor i in range(n+1):\n \n L = 1 # Initial product value\n for j in range(n+1):\n if j == i: continue # j == i gives ZeroDivisionError\n L *= (xp - X[j]) / (X[i] - X[j])\n \n yp += Y[i]*L\n\n\n# ~~~~~~~~~~~~~~~~~~~ Method 2: Using numpy array, prod ~~~~~~~~~~~~~~~~~~~~\n\nfrom numpy import array, prod\n\nX = array(X, float)\nY = array(Y, float)\n\nyp = 0\nfor Xi, Yi in zip(X, Y):\n yp += Yi * prod((xp - X[X != Xi]) / (Xi - X[X != Xi]))\n\n\nprint(\"The Y = %.1f\"% yp)\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~ Plotting the function ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nfrom numpy import append, linspace\nfrom matplotlib.pyplot import plot, xlabel, ylabel, show\n\nxplot = linspace(X[0], X[-1]) # Divides from 1st to last element of X\nyplot = array([], float) # into 50 points\n\nfor xp1 in xplot:\n\n yp1 = 0\n for Xi, Yi in zip(X, Y):\n yp1 += Yi * prod((xp1 - X[X != Xi]) / (Xi - X[X != Xi]))\n\n yplot = append(yplot, yp1)\n\n# pyplot.\nplot(X, Y, 'ro', xplot, yplot, 'b-', xp, yp, 'bo')\nxlabel('x')\nylabel('y')\nshow()\n", "meta": {"hexsha": "01acfc726f796e3fbadf4e487ed33f6fb70f98ea", "size": 1850, "ext": "py", "lang": "Python", "max_stars_repo_path": "2. Interpolation and Curve Fitting/2. Lagrange's Interpolation Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2. Interpolation and Curve Fitting/2. Lagrange's Interpolation Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2. Interpolation and Curve Fitting/2. Lagrange's Interpolation Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6944444444, "max_line_length": 76, "alphanum_fraction": 0.4594594595, "include": true, "reason": "from numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692264378964, "lm_q2_score": 0.9591542859873614, "lm_q1q2_score": 0.9367764745298691}} {"text": "''' \nExercise 3\n5.0/5.0 points (graded)\n\nWrite a function, stdDevOfLengths(L) that takes in a list of strings, L, and outputs the standard deviation of the lengths of the strings. Return float('NaN') if L is empty.\n\nRecall that the standard deviation is computed by this equation:\n\n∑t in X(t−μ)2N−−−−−−−−−−−−−√\n\nwhere:\n\n μ is the mean of the elements in X.\n\n ∑t in X(t−μ)2 means the sum of the quantity (t−μ)2 for t in X.\n\n That is, for each element (that we name t) in the set X, we compute the quantity (t−μ)2. We then sum up all those computed quantities.\n\n N is the number of elements in X.\n\n Test case: If L = ['a', 'z', 'p'], stdDevOfLengths(L) should return 0.\n\n Test case: If L = ['apples', 'oranges', 'kiwis', 'pineapples'], stdDevOfLengths(L) should return 1.8708.\n\nNote: If you want to use functions from the math library, be sure to import math. If you want to use numpy arrays, you should add the following lines at the beginning of your code for the grader:\nimport os\nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\nThen, do import numpy as np and use np.METHOD_NAME in your code.\n'''\nimport numpy as np\n\n\ndef stdDevOfLengths(L):\n \"\"\"\n L: a list of strings\n\n returns: float, the standard deviation of the lengths of the strings,\n or NaN if L is empty.\n \"\"\"\n if L == [] or L is None:\n return np.nan\n else:\n mean = sum(len(string) for string in L) / len(L)\n std_dev = (sum((len(string) - mean) **\n 2 for string in L) / len(L)) ** 0.5\n return std_dev\n", "meta": {"hexsha": "3c0223a096f5172af3da02e5456fe3ce6cc41afa", "size": 1546, "ext": "py", "lang": "Python", "max_stars_repo_path": "unit_03/lecture_07/exercise_03.py", "max_stars_repo_name": "alexmalme/mit_6002", "max_stars_repo_head_hexsha": "744a469fc024bb495497225a0d24251afa544fe5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_03/lecture_07/exercise_03.py", "max_issues_repo_name": "alexmalme/mit_6002", "max_issues_repo_head_hexsha": "744a469fc024bb495497225a0d24251afa544fe5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_03/lecture_07/exercise_03.py", "max_forks_repo_name": "alexmalme/mit_6002", "max_forks_repo_head_hexsha": "744a469fc024bb495497225a0d24251afa544fe5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8936170213, "max_line_length": 195, "alphanum_fraction": 0.6520051746, "include": true, "reason": "import numpy", "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138183570424, "lm_q2_score": 0.9546474205747175, "lm_q1q2_score": 0.9333719747548085}} {"text": "# math module\nimport math\n\n# we can see all the methods of math module.\nprint(dir(math))\n\n# we can see that we have different important methods here.\n# ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh',\n# 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh',\n# 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',\n# 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', \n# 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm',\n# 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n\n# calculate natural logarithm\nprint(math.log(10))\n\n# calculate common logarithm\nprint(math.log10(100))\n\n# calculate 2 based logarithm\nprint(math.log2(1024))\n\n# calculate factorial of any number\nprint(math.factorial(9))\n\n# calculate square root of any positive number\nprint(math.sqrt(100))\n\n# calculate square root of any negative number.\n# here the square root of any negative number is a complex number.\nimport cmath # we need to import cmath module which stands for complexmath\nprint(cmath.sqrt(-20))\n\n# using floor method\n# floor method rounds a number to its lower nearest integer.\nprint(math.floor(2.34))\n\n# using ceil method\n# ceil method rounds a number to its higher nearest integer.\nprint(math.ceil(2.34))\n\n# print the value of pi\nimport math\nprint(math.pi)\n# print the value of tau\nprint(math.tau)\n# print the value of e\nprint(math.e)\n\n# calculate the area of a circle.\ndef circle_area(radius):\n area=math.pi*(radius**2)\n return area\nprint(circle_area(10))\n\n# using Euelers constant\nprint(math.e)\n\n# convert degrees to radians\nprint(math.radians(180))\n\n# convert radians to degrees\nprint(math.degrees(3))\n\n# basic trigonometry\n# using sin method\nprint(math.sin(math.pi/2))# here the arguement is given in radians.\n\n# using cos method\nprint(math.cos(0))\n\n# using tan method\nprint(math.tan(math.pi/4))\n\n# using asin(arcsin) method\nprint(math.asin(1))# here the arguement is given in radians.\n# we can convert it to degrees.\nprint(math.degrees(math.asin(1)))\n\n# using acos(arccos) method\nprint(math.acos(1))\n\n# using atan(arctan) method\nprint(math.atan(1))\n\n# calculate gcd of numbers\nprint(math.gcd(120,90))\n\n# we can use the gamma() function.\nprint(math.gamma(100))\n\n# we can even find the remainder of float using the remainder() function.\nprint(math.remainder(100.123,3.1))\n\n# we can even find the power of float using pow() function.\nprint(math.pow(2.33,4.573))\n# we can do it in this way too.\nprint(2.33**4.573)\n\n# we can find the hypotnuse by hypot() method.\nprint(math.hypot(4,3))\n# it just take the co-ordinate and calculate the length of the line from origin to that co-ordinate.\n\n# we have infinite() and isinf() function to determine if a value is finite or infinity.\nprint(math.isfinite(334))\nprint(math.isinf(77))\n# we can create infinite value by inf attribute.\np=math.inf\nprint(math.isinf(p))\n\n# isqurt() returns the integer part of the square root of the input.\nprint(math.isqrt(66))\n\n# we can create nan values with nan attribute.\na=math.nan\n# we can examine if it is a nan or not by isnan() method.\nprint(math.isnan(a))\n\n# we can find the euclidian distance beetween two point in any dimention.\nl=[0,10,20,30,5]\nr=[0,10,24,3,89]\nprint(math.dist(l,r))\n\n# using linear algebra we can calculate this manually,\nimport numpy as np\na1=np.array(l)\na2=np.array(r)\n\na3=a1-a2\n\nres=0\nfor elements in a3:\n res += elements**2\n\nprint(np.sqrt(res))\n\n# we can find the number of combination using comb() method.\nn=10\nr=4\nprint(math.comb(n,r))\n\n# we can find the number of permutation using perm() method.\nn=10\nr=4\nprint(math.perm(n,r))\n\n# copysign() returns the magnitute(value) of first arguement and sign(+-) of second arguement.\nprint(math.copysign(20.56,-56.7))\n\n# we haave some more functions and constants in math module.\n# we will use them later if needed.", "meta": {"hexsha": "8b98ca9308407590f9209d11c82219f242b6cde1", "size": 3984, "ext": "py", "lang": "Python", "max_stars_repo_path": "03. math module.py", "max_stars_repo_name": "ahammadshawki8/Standerd-Libraries-of-Python", "max_stars_repo_head_hexsha": "cec8e21e5ac667b8a208c86709ee2ef783d28149", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03. math module.py", "max_issues_repo_name": "ahammadshawki8/Standerd-Libraries-of-Python", "max_issues_repo_head_hexsha": "cec8e21e5ac667b8a208c86709ee2ef783d28149", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03. math module.py", "max_forks_repo_name": "ahammadshawki8/Standerd-Libraries-of-Python", "max_forks_repo_head_hexsha": "cec8e21e5ac667b8a208c86709ee2ef783d28149", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2105263158, "max_line_length": 101, "alphanum_fraction": 0.7078313253, "include": true, "reason": "import numpy", "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707986486796, "lm_q2_score": 0.9525741278322103, "lm_q1q2_score": 0.9310181360914368}} {"text": "# Question 01, Lab 04\n# AB Satyaprakash - 180123062\n\n# imports ----------------------------------------------------------------------------\nfrom sympy.abc import x\nfrom sympy import cos, exp, pi, evalf, simplify\n\n# functions --------------------------------------------------------------------------\n\n\ndef midpointRule(f, a, b):\n return ((b-a)*f.subs(x, (b-a)/2)).evalf()\n\n\ndef trapezoidalRule(f, a, b):\n return (((b-a)/2)*(f.subs(x, a)+f.subs(x, b))).evalf()\n\n\ndef simpsonRule(f, a, b):\n return (((b-a)/6)*(f.subs(x, a)+4*f.subs(x, (a+b)/2)+f.subs(x, b))).evalf()\n\n\n# program body\n# part (a) I = integrate cosx/(1+cos^2x) from 0 to π/2 -- exact value ≈ 0.623225\nf = cos(x)/(1 + cos(x)**2)\na, b = 0, pi/2\n\nprint('To integrate {} from {} to {}'.format(simplify(f), a, b))\nprint('Evaluated value of integral using Midpoint rule is', midpointRule(f, a, b))\nprint('Evaluated value of integral using Trapezoidal rule is',\n trapezoidalRule(f, a, b))\nprint('Evaluated value of integral using Simpson rule is', simpsonRule(f, a, b))\nprint('Exact value ≈ 0.623225\\n')\n\n\n# part (b) I = integrate 1/(5+4cosx) from 0 to π -- exact value ≈ 1.047198\nf = 1/(5 + 4*cos(x))\na, b = 0, pi\n\nprint('To integrate {} from {} to {}'.format(simplify(f), a, b))\nprint('Evaluated value of integral using Midpoint rule is', midpointRule(f, a, b))\nprint('Evaluated value of integral using Trapezoidal rule is',\n trapezoidalRule(f, a, b))\nprint('Evaluated value of integral using Simpson rule is', simpsonRule(f, a, b))\nprint('Exact value ≈ 1.047198\\n')\n\n# part (c) I = integrate exp(-x^2) from 0 to 1 -- exact value ≈ 0.746824\nf = exp(-x**2)\na, b = 0, 1\n\nprint('To integrate {} from {} to {}'.format(simplify(f), a, b))\nprint('Evaluated value of integral using Midpoint rule is', midpointRule(f, a, b))\nprint('Evaluated value of integral using Trapezoidal rule is',\n trapezoidalRule(f, a, b))\nprint('Evaluated value of integral using Simpson rule is', simpsonRule(f, a, b))\nprint('Exact value ≈ 0.746824\\n')\n", "meta": {"hexsha": "7b07511b3c63cabc1ba6d7bbdff573d783a44ca0", "size": 2003, "ext": "py", "lang": "Python", "max_stars_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q1.py", "max_stars_repo_name": "Imperial-lord/IITG", "max_stars_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-02T03:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:38:05.000Z", "max_issues_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q1.py", "max_issues_repo_name": "Imperial-lord/IITG", "max_issues_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q1.py", "max_forks_repo_name": "Imperial-lord/IITG", "max_forks_repo_head_hexsha": "df4233905d2954511d5b16666f0d44cc38b9df90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-04T17:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:38:09.000Z", "avg_line_length": 35.1403508772, "max_line_length": 86, "alphanum_fraction": 0.6050923615, "include": true, "reason": "from sympy", "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.982013788985129, "lm_q2_score": 0.9458012747599251, "lm_q1q2_score": 0.9287898934539591}} {"text": "from numpy import exp, linspace, empty\nf = lambda x: exp(x-2) - 3 # Analytical Solution\n\ndy = lambda x, y: y+3 # Equation to be solved, y' = y+3\nx = 2 # Lower limit, [2\nxn = 4 # Upper limit, 4]\ny = -2 # Initial condition, y(2) = -2\n\nh = 0.1 # Width of each division, step size\nn = int((xn-x)/h) # Number of divisions of the domain\n\n# Plot Arrays\nxp = linspace(x, xn, n+1) # Divides from x to xn into n+1 points\nyp = empty(n+1, float)\nyp[0] = y\n\n\nprint('x \\t\\ty(RK4) \\t\\ty(Analytical)') # Header of Output\nprint('%f \\t% f \\t% f' % (x, y, f(x))) # Initial x and y\n\nfor i in range(1, n+1):\n K1 = h * dy(x,y)\n K2 = h * dy(x + h/2, y + K1/2)\n K3 = h * dy(x + h/2, y + K2/2)\n K4 = h * dy(x + h, y + K3)\n \n y += 1/6*(K1 + 2*K2 + 2*K3 + K4) # y(x+h) = y(x) + 1/6(K1+2K2+2K3+K4)\n yp[i] = y\n x += h # x for next step, x = x + h\n print('%f \\t% f \\t% f' % (x, y, f(x)))\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~ Plotting the function ~~~~~~~~~~~~~~~~~~~~~~~~~~\nimport matplotlib.pyplot as plt\n\n# pyplot.\nplt.plot(xp, yp, 'ro', xp, f(xp)) # Default plot is continuous blue line\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(['RK4', 'Analytical'])\nplt.show()\n\n\n\"\"\"\nTaylor's series can be written as\ny(x+h) = y(x) + y'(x)h + y''(x)/2! h^2 + y'''(x)/3! h^3 + ...\n\nApproximate solution of Euler's method is obtained by\ntrancating the series at the first derivative term\ny(x+h) = y(x) + y'(x)h\n\nIncluding the second, third, and forth derivatives\n\nK1 = h y'(x,y)\nK2 = h y'(x + h/2, y + K1/2)\nK3 = h y'(x + h/2, y + K2/2)\nK4 = h y'(x + h, y + K3)\ny(x+h) = y(x) + 1/6 (K1 + 2 K2 + 2 K3 + K4)\n\nThe initial condition is the value of y(x) at initial domain x\n\nFind the numerical solution of the following differential equation\nover the domain [2,4]: y' = y+3, y(2) = -2\n\nAnalytical Solution: y = e^(x-2) - 3\n\n\"\"\"\n", "meta": {"hexsha": "c3c4c7f66299796377d7936a4dfa4a87b3cbf847", "size": 1926, "ext": "py", "lang": "Python", "max_stars_repo_path": "6. Ordinary Differential Equations/3. b. Plotting Fourth Order Runge-Kutta (RK4) Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "6. Ordinary Differential Equations/3. b. Plotting Fourth Order Runge-Kutta (RK4) Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6. Ordinary Differential Equations/3. b. Plotting Fourth Order Runge-Kutta (RK4) Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3235294118, "max_line_length": 76, "alphanum_fraction": 0.5212876428, "include": true, "reason": "from numpy", "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9817357184418847, "lm_q2_score": 0.9449947057037211, "lm_q1q2_score": 0.92773505632782}} {"text": "import numpy as np\n\n# Arithmetic operators on arrays apply element wise. A new array is created and filled with the result.\nprint(\"<---- Arithmatic Operation --->\")\na = np.array([12,45,85,96])\nb = np.arange(5,9)\nprint(\"Subtraction : \",a-b)\nprint(\"Power of 2 of b array : \",b**2)\nprint(\"Sin of a : \",10*np.sin(a))\nprint(\"Less than operator : \",a<79)\n\n# Unlike in many matrix languages, the product operator * operates element wise in NumPy arrays.\n# The matrix product can be performed using the @ operator (in python >=3.5) or the dot function\n# or method\nprint(\"<---- Product of array ---->\")\na = np.array([(1,2),(3,4)])\nb = np.array([[5,6],[7,8]])\nprint(\"Element wise product : \",a*b)\nprint(\"Matrix product : \",a@b)\nprint(\"Another matrix product : \",a.dot(b))\n\n# Some operations, such as += and *=, act in place to modify an existing array rather than\n# create a new one.\nprint(\"<---- Assignment operator --->\")\na = np.ones(shape=(2,3),dtype=int)\nb = np.random.rand(2,3)\na *= 3\nprint(\"Multiply by 3 to each element of Array a : \",a)\n# a += b this is not possible here because a in type of int and b is float because randome gives\n# float default\nb += a\nprint(\"Adding each element of a with b : \",b)\n\n# When operating with arrays of different types, the type of the resulting array corresponds to\n# the more general or precise one (a behavior known as upcasting).\nprint(\"<---- Upcasting of array ---->\")\na = np.ones(3,dtype=np.int32)\nb = np.linspace(0,np.pi,3)\nprint(\"dtype of b : \",b.dtype)\nc = a + b\nprint(\"Addition of a and b : \",c)\nprint(\"dtype of c : \",c.dtype)\nd = np.exp(c*1j)\nprint(\"exp of c : \",d)\nprint(\"dtype of d : \",d.dtype)\n\n# Many unary operations, such as computing the sum of all the elements in the array, are\n# implemented as methods of the ndarray class.\nprint(\"<---- Common ndarray operations ---->\")\na = np.random.random((3,2))\nprint(\"Sum : \",a.sum())\nprint(\"Min : \",a.min())\nprint(\"Max : \",a.max())\n\n# By default, these operations apply to the array as though it were a list of numbers,\n# regardless of its shape. However, by specifying the axis parameter you can apply an operation\n# along the specified axis of an array:\nprint(\"<---- Common ndarray operations using axis ---->\")\nb = np.arange(12).reshape(3,4)\nprint(\"b Array : \",b)\nprint(\"Sum of each column : \",b.sum(axis=0))\nprint(\"Sum of each row : \",b.sum(axis=1))\nprint(\"Cumulative sum along each row : \",b.cumsum(axis=1))\n", "meta": {"hexsha": "ed0c7792d04e56049b95df87af164e1288e423b5", "size": 2404, "ext": "py", "lang": "Python", "max_stars_repo_path": "python-numpy/Python_NumPy/npbasic/BasicOperation.py", "max_stars_repo_name": "theumang100/tutorials-1", "max_stars_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-04-23T05:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T16:37:51.000Z", "max_issues_repo_path": "python-numpy/Python_NumPy/npbasic/BasicOperation.py", "max_issues_repo_name": "theumang100/tutorials-1", "max_issues_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T03:18:10.000Z", "max_forks_repo_path": "python-numpy/Python_NumPy/npbasic/BasicOperation.py", "max_forks_repo_name": "theumang100/tutorials-1", "max_forks_repo_head_hexsha": "497f54c2adb022c316530319a168fca1c007d4b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-04-28T14:06:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T18:32:28.000Z", "avg_line_length": 37.5625, "max_line_length": 103, "alphanum_fraction": 0.6738768719, "include": true, "reason": "import numpy", "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877675527111, "lm_q2_score": 0.9553191313174709, "lm_q1q2_score": 0.9273165948789511}} {"text": "\"\"\"\n### Merge sort\nComplexity: \n- $6n$ operations per level\n- $\\log_2(n)$ recursive calls\n- Total in time : $6n \\log_2(n) + 6n = O(n\\log(n))$\n- In memory: $O(n)$ as need not in place\n\nInversions algorithm\nComplexity: \nsame as merge sort, $O(n\\log(n))$ in time and $O(n)$ in memory\n\"\"\"\n\nimport numpy as np\n\n\ndef merge_sort(A):\n def merge_sort_(A, l, r):\n if l < r:\n m = (l + r - 1) // 2\n merge_sort_(A, l, m)\n merge_sort_(A, m + 1, r)\n combine(A, l, m, r)\n\n def combine(A, l, m, r):\n n_l = m - l + 1\n n_r = r - m\n L = A[l : m + 1]\n R = A[m + 1 : r + 1]\n i, j, k = 0, 0, l\n while i < n_l and j < n_r:\n if L[i] <= R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n j += 1\n k += 1\n while i < n_l:\n A[k] = L[i]\n k += 1\n i += 1\n while j < n_r:\n A[k] = R[j]\n k += 1\n j += 1\n\n return merge_sort_(A, 0, len(A) - 1)\n\n\ndef count_inversions(A):\n def sort_and_count_inversions(A, l, r):\n if r <= l:\n return 0\n else:\n m = (l + r - 1) // 2\n x = sort_and_count_inversions(A, l, m)\n y = sort_and_count_inversions(A, m + 1, r)\n z = combine_and_count_inv_split(A, l, m, r)\n return x + y + z\n\n def combine_and_count_inv_split(A, l, m, r):\n n_l = m - l + 1\n n_r = r - m\n L = A[l : m + 1]\n R = A[m + 1 : r + 1]\n i, j, k = 0, 0, l\n count = 0\n while i < n_l and j < n_r:\n if L[i] <= R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n count += n_l - i\n j += 1\n k += 1\n while i < n_l:\n A[k] = L[i]\n k += 1\n i += 1\n while j < n_r:\n A[k] = R[j]\n k += 1\n j += 1\n return count\n\n return sort_and_count_inversions(A, 0, len(A) - 1)\n\n\nif __name__ == \"__main__\":\n A = np.loadtxt(\"./Course_1/countinv.txt\").tolist()\n # A = [1, 23, 5, 2, 4, 6]\n count_inversions(A)\n", "meta": {"hexsha": "4288a9929c057a4c012430e03bf585ab28ccbd91", "size": 2236, "ext": "py", "lang": "Python", "max_stars_repo_path": "Course_1/mergesort_countinv.py", "max_stars_repo_name": "julesbertrand/Stanford-alg", "max_stars_repo_head_hexsha": "068a76d3b3108df6fb09136fbfe373648bbfbe90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Course_1/mergesort_countinv.py", "max_issues_repo_name": "julesbertrand/Stanford-alg", "max_issues_repo_head_hexsha": "068a76d3b3108df6fb09136fbfe373648bbfbe90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Course_1/mergesort_countinv.py", "max_forks_repo_name": "julesbertrand/Stanford-alg", "max_forks_repo_head_hexsha": "068a76d3b3108df6fb09136fbfe373648bbfbe90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5368421053, "max_line_length": 62, "alphanum_fraction": 0.3868515206, "include": true, "reason": "import numpy", "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399060540359, "lm_q2_score": 0.9553191290913013, "lm_q1q2_score": 0.9268887420611676}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n## Running a Multivariate Regression in Python\n# *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).*\n# Let’s continue working on the file we used when we worked on univariate regressions.\n# *****\n# Run a multivariate regression with 5 independent variables – from Test 1 to Test 5.\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport statsmodels.api as sm \nimport matplotlib.pyplot as plt\ndata = pd.read_excel('Section-13_IQ_data.xlsx')\ndata.head()\n# ### Multivariate Regression:\n# Independent Variables: *Test 1, Test 2, Test 3, Test 4, Test 5*\n# In[4]:\nX = data[['Test 1', 'Test 2', 'Test 3', 'Test 4', 'Test 5']]\nX = data.iloc[:,[1,2,3,4,5]]\nY = data.iloc[:,0]\n# In[5]:\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n# The p-value of the variable Test 1 in the univariate regression looked very promising. Is it still low? If not – what do you think would be the reason for the change?\n# Try regressing Test 1 and Test 2 on the IQ score first. Then, regress Test 1, 2, and 3 on IQ, and finally, regress Test 1, 2, 3, and 4 on IQ. What is the Test 1 p-value in these regressions?\n# Independent Variables: *Test 1, Test 2*\n# In[6]:\nX = data[['Test 1', 'Test 2']]\nX = data.iloc[:,[1,2]]\nY = data.iloc[:,0]\n# In[7]:\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n# Independent Variables: *Test 1, Test 2, Test 3*\n# In[8]:\nX = data[['Test 1', 'Test 2', 'Test 3']]\nX = data.iloc[:,[1,2,3]]\nY = data.iloc[:,0]\n# In[9]:\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n# Independent Variables: *Test 1, Test 2, Test 3, Test 4*\n# In[10]:\nX = data[['Test 1', 'Test 2', 'Test 3', 'Test 4']]\nX = data.iloc[:,[1,2,3,4]]\nY = data.iloc[:,0]\n# In[11]:\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n# It seems it increases a lot when we add the result from Test 4. \n# ****\n# Run a regression with only Test 1 and Test 4 as independent variables. How would you interpret the p-values in this case?\n# Independent Variables: *Test 1, Test 4*\n# In[12]:\nX = data[['Test 1', 'Test 4']]\nX = data.iloc[:,[1,4]]\nY = data.iloc[:,0]\n# In[13]:\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n# Independent Variables: *Test 4*\n# In[14]:\nX = data[['Test 4']]\nX = data.iloc[:,4]\nY = data.iloc[:,0]\n# In[15]:\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\nreg.summary()\n# ***Suggested Answer:***\n# *Test 1 and Test 4 are correlated, and they contribute to the preparation of the IQ test in a similar way.*\n", "meta": {"hexsha": "a6864541cbaae292db5f7f3d8899a2e21d6bdcc4", "size": 2557, "ext": "py", "lang": "Python", "max_stars_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-16_97-RunningaMultivariateRegressioninPython-Solution.py", "max_stars_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_stars_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-04T11:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-10T15:36:42.000Z", "max_issues_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-16_97-RunningaMultivariateRegressioninPython-Solution.py", "max_issues_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_issues_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-30T16:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:37:21.000Z", "max_forks_repo_path": "InvestmentFundamentalsAndDataAnalytics/Examples/Section-16_97-RunningaMultivariateRegressioninPython-Solution.py", "max_forks_repo_name": "enriqueescobar-askida/Kinito.Finance", "max_forks_repo_head_hexsha": "5308748b64829ac798a858161f9b4a9e5829db44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-14T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T11:26:16.000Z", "avg_line_length": 33.2077922078, "max_line_length": 192, "alphanum_fraction": 0.6613218616, "include": true, "reason": "import numpy,from scipy,import statsmodels", "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692352660529, "lm_q2_score": 0.9489172592508286, "lm_q1q2_score": 0.9267782939232656}} {"text": "import math\nimport numpy as np\n\ndef distance_calculator(x1, y1, x2, y2):\n \"\"\"\n function to return Euclidean distance between two coordinates (x1,y1) and (x2,y2)\n \"\"\"\n return math.sqrt((x2 - x1)**2 + (y2-y1)**2)\n\n\ndef regular_polygon(side_number, side_length, dir_counter_clock=True):\n \"\"\"\n function to return coordinates of vertices on the regular polygon\n \"\"\"\n\n # unit radius\n radius = 1\n\n # using cosine 2 rule\n init_side_length = math.sqrt(2*(radius**2) - 2*(radius**2)*math.cos(2*math.pi/side_number))\n\n # we want the the polygon's side length as input target; thus multiply this ratio\n ratio = side_length/init_side_length\n\n \n # find coordinate list\n coordinate_list = []\n for i in range(side_number):\n coordinate_list.append((radius * ratio * math.cos(2*math.pi * i/side_number), radius * ratio * math.sin(2*math.pi * i/side_number)))\n \n # append the starting point at the end to make the robot return home\n coordinate_list.append(coordinate_list[0])\n \n # clock-wise rotation coordinates\n if dir_counter_clock is False:\n coordinate_list = coordinate_list[::-1] # reverse the cooridnate list\n\n print(\"======================================================\")\n print(\"side number: {}\".format(side_number))\n print(\"side length: {}\".format(side_length))\n print(\"counter-clock direction?: {}\".format(dir_counter_clock))\n print(\"double check side by coordinate: {}\".format(distance_calculator(coordinate_list[0][0], \n coordinate_list[0][1], coordinate_list[1][0], coordinate_list[1][1])))\n \n print(\"coordinate list: {}\".format(coordinate_list))\n print(\"======================================================\")\n\n return coordinate_list\n\n\ndef check_vector_angle(vec1, vec2):\n \"\"\"\n check angle between two vectors by using vec 1 as base.\n - arg: vec1, vec2 format np.array([x,y]) 1x2 \n - return: angle between the vectors abs 0 to pi (+: if coincide with check vector, -: if not)\n \"\"\"\n\n # inner dot calculation\n inner_dot = np.dot(vec1, vec2)\n\n # vector length calculation\n vec1_len = np.linalg.norm(vec1)\n vec2_len = np.linalg.norm(vec2)\n\n # between angle calculation\n between_angle = math.acos(round(np.asscalar(inner_dot / (vec1_len * vec2_len)),6))\n\n # check vector (assuming \"between angle\" is correct, we get rotation vector of vec1 based on that angle)\n # length normalization and magnitude reflection\n check_vector = [vec1[0] * math.cos(between_angle) - vec1[1] * math.sin(between_angle),\n vec1[0] * math.sin(between_angle) + vec1[1] * math.cos(between_angle)]\n check_vector_normalized = [check_vector[i] / vec1_len for i in range(len(check_vector))]\n vec2_normalized = [vec2[i] / vec2_len for i in range(len(check_vector))]\n\n # check if the vector is the same as what we want\n # note that 0.1 is just a threshhold for comparison\n if abs(check_vector_normalized[0] - vec2_normalized[0]) < 0.1 and abs(check_vector_normalized[1] - vec2_normalized[1]) < 0.1:\n return between_angle\n return -between_angle\n", "meta": {"hexsha": "0c49127859db132321b679c69c2a406d8f5b2dfa", "size": 3156, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/simple_shapes/aux_function.py", "max_stars_repo_name": "MingiJeong/simple_shapes", "max_stars_repo_head_hexsha": "a6604819a1d66d415fe20a888c7802afd5c6b65b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simple_shapes/aux_function.py", "max_issues_repo_name": "MingiJeong/simple_shapes", "max_issues_repo_head_hexsha": "a6604819a1d66d415fe20a888c7802afd5c6b65b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simple_shapes/aux_function.py", "max_forks_repo_name": "MingiJeong/simple_shapes", "max_forks_repo_head_hexsha": "a6604819a1d66d415fe20a888c7802afd5c6b65b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.45, "max_line_length": 140, "alphanum_fraction": 0.6486058302, "include": true, "reason": "import numpy", "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9867771809697151, "lm_q2_score": 0.9390248157222396, "lm_q1q2_score": 0.9266082605189978}} {"text": "import numpy as np\nimport matplotlib.pyplot as mp\n\n# Equiation : f(U) + H(U) * V = 0\n# <=> H(U) * V = -f(U)\n\n# Transforms an array of functions to a function returning an array of the values of each function\ndef function_array(f):\n\treturn lambda U: np.vectorize(lambda fn: fn(U))(f)\n\n# Produces a value indicating how x is near to a root of f. Returns a value close to 0 if x is near a root and a value far from 0 if x is far from any root.\ndef phi(f, x):\n\tfx = f(x)\n\treturn np.matmul(fx.T, fx)\n\n# Finds a root of f where J is the Jacobian matrix of j.\n# Parameters:\n# - U0 the starting point of the algorithm\n# - N the maximum number if iterations\n# - epsilon the desired accuracy\n# - backtracking wether backtraking should be used\n# - track_phi wether the value of phi(Un) should be tracked and returned in an array\n# Returns:\n# - A root of f if track_phi is False\n# - A root of f and the array of phi(Un) if track_phi is True\ndef Newton_Raphson(f, J, U0, N, epsilon, backtracking = True, track_phi = False):\n\n\tUn = U0\n\tpreviousPhi = phi(f, U0)\n\tif track_phi:\n\t\tphiArray = [previousPhi]\n\n\tfor i in range(N):\n\t\tfUn = f(Un)\n\t\tif np.linalg.norm(fUn) < epsilon:\n\t\t\tbreak;\n\n\t\tV = np.linalg.lstsq(J(Un), -fUn, rcond=-1)[0]\n\n\t\t# Backtracking\n\t\tstep = 1.0\n\t\tnewUn = Un + V\n\t\tnewPhi = phi(f, newUn)\n\t\tif backtracking:\n\t\t\twhile newPhi >= previousPhi:\n\t\t\t\tstep *= 0.9;\n\t\t\t\tnewUn = Un + step * V\n\t\t\t\tnewPhi = phi(f, newUn)\n\n\t\tUn = newUn\n\t\tpreviousPhi = newPhi\n\t\tif track_phi:\n\t\t\tphiArray.append(newPhi)\n\n\tif track_phi:\n\t\treturn (Un, phiArray)\n\telse:\n\t\treturn Un\n\n# Tests the Newton_Raphson algorithm with simple cases\ndef test_Newton_Raphson():\n\t# f1(x) = x² - 2x + 1\n\t# f1'(x) = 2x - 2\n\tf1 = function_array([lambda x: x**2 - 2*x + 1])\n\tJ1 = function_array([[lambda x: 2*x - 2]])\n\texpected = 1\n\troot1 = Newton_Raphson(f1, J1, np.array([0]), 40, 10e-6)\n\tprint(\"f(x) = x² - 2x + 1\")\n\tprint(\"Root:\", root1)\n\tprint(\"Relative error:\", np.abs(root1 - expected))\n\n\n\t# f2(x, y) = (x² + y, x + 3y + 4)\n\t# df2/dx(x, y) = (2*x, 1)\n\t# df2/dy(x, y) = (1, 3)\n\tf2 = function_array([lambda z: z[0]**2 + z[1], lambda z: z[0] + 3*z[1] + 4])\n\tJ2 = function_array([[lambda z: 2*z[0], lambda z: 1],\n\t\t\t\t\t\t [lambda z: 1, lambda z: 3]])\n\troot2 = Newton_Raphson(f2, J2, np.array([1, 4]), 40, 1e-10)\n\tprint(\"f(x, y) = (x² + y, x + 3y + 4)\")\n\tprint(\"Root:\",root2)\n\tprint(\"f(root) =\", f2(root2))\n\n# Tests the effets of backtracking on the convergence speed\ndef test_backtracking():\n\t# f(x) = x^3 - 2x^2 + 1\n\t# f'(x) = 3x^2 - 4x\n\tf = function_array([lambda x: x**3 - 2*x**2 + 1])\n\tJ = function_array([[lambda x: 3*(x**2) - 4*x]])\n\troot0, phiArray0 = Newton_Raphson(f, J, np.array([0.01]), 40, 10e-10, False, True)\n\troot1, phiArray1 = Newton_Raphson(f, J, np.array([0.01]), 40, 10e-10, True, True)\n\n\n\tmp.plot(range(len(phiArray0)), phiArray0, label = \"Without Backtracking\", linewidth = 1.0)\n\tmp.plot(range(len(phiArray1)), phiArray1, label = \"With Backtracking\", linewidth = 1.0)\n\tmp.yscale('log')\n\tmp.legend()\n\tmp.title(\"The value of $phi(U_n)$ in each iteration, with $f(x) = x^3 - 2x^2 + 1$, $U_0 = 0.01$ and $\\\\epsilon = 10^{-10}$\")\n\tmp.xlabel(\"n, the number of iterations\")\n\tmp.ylabel(\"$phi(U_n)$\")\n\tmp.show()\n\n\nif __name__ == \"__main__\":\n\ttest_Newton_Raphson()\n\ttest_backtracking()", "meta": {"hexsha": "d56ec4a5bd145270be1ea360d073996ec2e64652", "size": 3249, "ext": "py", "lang": "Python", "max_stars_repo_path": "newton_raphson.py", "max_stars_repo_name": "ImadProjects/Non-linear-systems-of-equations-Newton-Raphson-Method", "max_stars_repo_head_hexsha": "54a0082f0cee3797b98e840847fa11db3f117770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newton_raphson.py", "max_issues_repo_name": "ImadProjects/Non-linear-systems-of-equations-Newton-Raphson-Method", "max_issues_repo_head_hexsha": "54a0082f0cee3797b98e840847fa11db3f117770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newton_raphson.py", "max_forks_repo_name": "ImadProjects/Non-linear-systems-of-equations-Newton-Raphson-Method", "max_forks_repo_head_hexsha": "54a0082f0cee3797b98e840847fa11db3f117770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6509433962, "max_line_length": 156, "alphanum_fraction": 0.6374269006, "include": true, "reason": "import numpy", "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426405416756, "lm_q2_score": 0.9511422163574368, "lm_q1q2_score": 0.9264530759514594}} {"text": "import numpy as np\nfrom math import sqrt\n\n\n# Fibonacci version 1 in exponential time. \n# The running time of fib1(n) is proportional to 2^(0.69n) ~ (1.6)^n, so it takes 1.6 times longer to compute Fn+1 than Fn.\ndef fib1(n):\n if n == 0: return 0\n if n == 1: return 1\n return fib1(n-1) + fib1(n-2)\n\n\n# Fibonacci version 2 in linear time (Polynomial)\n# Why is fib1(n) so slow? because many computations are repeated during the recursion. A more sensible scheme would store the intermediate results, the value of F0.....Fn-1 to an array as soon as they are know so that they don't have to be recomputed during each recursion call.\ndef fib2(n):\n if n == 0: return 0\n f = np.zeros(n+1, dtype=np.int) # Creates an array holds F0 to Fn\n f[0] = 0\n f[1] = 1\n for i in range(2, n+1): # Loops from f2 to fn (range is exclusive on the 2nd argument)\n f[i] = f[i-1] + f[i-2]\n return f[n]\n\n\n# Fibonacci version 3 in constant time.\n# Of course, the fastest is using Binet's Fibonacci Number Formula: http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html\ndef fib3(n):\n return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))\n\n# Tests\nprint \"fib1(10) = \" + str(fib1(10))\nprint \"fib2(10) = \" + str(fib2(10))\nprint \"fib3(10) = \" + str(fib3(10))", "meta": {"hexsha": "1b85ed7d8c2cc7fb5d2d333dd5de3aa30aee10ef", "size": 1267, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python/Fibonacci.py", "max_stars_repo_name": "AlexOuyang/AlgorithmExercises", "max_stars_repo_head_hexsha": "55e7d211c0fa52d53fd7f04aead5f299be8e668c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/Fibonacci.py", "max_issues_repo_name": "AlexOuyang/AlgorithmExercises", "max_issues_repo_head_hexsha": "55e7d211c0fa52d53fd7f04aead5f299be8e668c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/Fibonacci.py", "max_forks_repo_name": "AlexOuyang/AlgorithmExercises", "max_forks_repo_head_hexsha": "55e7d211c0fa52d53fd7f04aead5f299be8e668c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3939393939, "max_line_length": 278, "alphanum_fraction": 0.6645619574, "include": true, "reason": "import numpy", "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9835969679646668, "lm_q2_score": 0.9399133468805265, "lm_q1q2_score": 0.924495918141208}} {"text": "import numpy as np\nimport scipy.integrate as spi\nimport matplotlib.pyplot as plt\n\n#t is the independent variable\nP = 3. #period value\nBT=-6. #initian value of t (begin time)\nET=6. #final value of t (end time)\nFS=1000 #number of discrete values of t between BT and ET\n\n#the periodic real-valued function f(t) with period equal to P\nf = lambda t: ((t % P) - (P / 2.)) ** 3\n\n#all discrete values of t in the interval from BT and ET\nt_range = np.linspace(BT, ET, FS)\ny_true = f(t_range) #the true f(t)\n\n#function that computes the real fourier couples of coefficients (a0, 0), (a1, b1)...(aN, bN)\ndef compute_real_fourier_coeffs(func, N):\n result = []\n for n in range(N+1):\n an = (2./P) * spi.quad(lambda t: func(t) * np.cos(2 * np.pi * n * t / P), 0, P)[0]\n bn = (2./P) * spi.quad(lambda t: func(t) * np.sin(2 * np.pi * n * t / P), 0, P)[0]\n result.append((an, bn))\n return np.array(result)\n\n#function that computes the real form Fourier series using an and bn coefficients\ndef fit_func_by_fourier_series_with_real_coeffs(t, AB):\n result = 0.\n A = AB[:,0]\n B = AB[:,1]\n for n in range(0, len(AB)):\n if n > 0:\n result += A[n] * np.cos(2. * np.pi * n * t / P) + B[n] * np.sin(2. * np.pi * n * t / P)\n else:\n result += A[0]/2.\n return result\n\nmaxN=8\nCOLs = 2 #cols of plt\nROWs = 1 + (maxN-1) // COLs #rows of plt\nplt.rcParams['font.size'] = 8\nfig, axs = plt.subplots(ROWs, COLs)\nfig.tight_layout(rect=[0, 0, 1, 0.95], pad=3.0)\nfig.suptitle('f(t) = ((t % P) - (P / 2.)) ** 3 where P=' + str(P))\n\n#plot, in the range from BT to ET, the true f(t) in blue and the approximation in red\nfor N in range(1, maxN + 1):\n AB = compute_real_fourier_coeffs(f, N)\n #AB contains the list of couples of (an, bn) coefficients for n in 1..N interval.\n\n y_approx = fit_func_by_fourier_series_with_real_coeffs(t_range, AB)\n #y_approx contains the discrete values of approximation obtained by the Fourier series\n\n row = (N-1) // COLs\n col = (N-1) % COLs\n axs[row, col].set_title('case N=' + str(N))\n axs[row, col].scatter(t_range, y_true, color='blue', s=1, marker='.')\n axs[row, col].scatter(t_range, y_approx, color='red', s=2, marker='.')\nplt.show()\n", "meta": {"hexsha": "fcb8024cbc75304e313c746140b3844d18994094", "size": 2236, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/python/fourier-series/fourier-series-func-rtor-using-definition-with-real-coeffs.py", "max_stars_repo_name": "ettoremessina/function-fitting", "max_stars_repo_head_hexsha": "6abf711a2f004b81614720e66cf66f35b4c14955", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/python/fourier-series/fourier-series-func-rtor-using-definition-with-real-coeffs.py", "max_issues_repo_name": "ettoremessina/function-fitting", "max_issues_repo_head_hexsha": "6abf711a2f004b81614720e66cf66f35b4c14955", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/python/fourier-series/fourier-series-func-rtor-using-definition-with-real-coeffs.py", "max_forks_repo_name": "ettoremessina/function-fitting", "max_forks_repo_head_hexsha": "6abf711a2f004b81614720e66cf66f35b4c14955", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6557377049, "max_line_length": 100, "alphanum_fraction": 0.6234347048, "include": true, "reason": "import numpy,import scipy", "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517443658749, "lm_q2_score": 0.9449947097701509, "lm_q1q2_score": 0.9242537243072197}} {"text": "# Importing numpy library\nimport numpy as np\n\n# Arrays to demonstrate unary ufuncs\nrandomint_arr = np.random.randint(-20,20,size = (2,3,4))\nrandomfloat_arr = np.random.randn(2,5,4)\n\n\n# Unary Ufuncs\n\"\"\" \n>> ufuncs operate element by element on whole arrays.\n>> ufuncs are highspeed because they are written in C.\nMost common unary ufuncs include :\nround, rint, fix, abs, absolute, fabs, sqrt, square, exp, exp2, log, log10, log2, \nlogp, sign, ceil, floor, modf, isnan, isinfinte, isinf, cos, cosh, \narccos, sin, sinh, arcsin, tan, tanh, arctan,logical_not\n\"\"\"\n\n# Round an array to the given number of decimals.\nprint(f'\\n Round to 2 decimals = \\n{np.round(randomfloat_arr,2)}')\n\n# Round elements of the array to the nearest integer.\nprint(f'\\n Round to nearest integer = \\n{np.rint(randomfloat_arr)}')\n\n# Round to nearest integer towards zero.\nprint(f'\\n Round to nearest integer towards zero = \\n{np.fix(randomfloat_arr,2)}')\n\n# Computes the absolute value of a integer array; cannot handle complex values like a+ib\nprint(f'\\nAbsolute value = \\n{np.abs(randomint_arr)}')\n\n# Calculates the absolute value for complex arrays too; absolute = sqrt(a^2+b^2)\nprint(f'\\nAbsolute value for complex numbers = \\n{np.absolute(4+3j)}')\n\n# Computes the absolute value of a floating point array\nprint(f'\\nAbsolute value for floating point= \\n{np.fabs(randomfloat_arr)}')\n\n# Return the fractional and integral parts of an array, element-wise.\nprint(f'\\n Fractional and integral parts =\\n {np.modf(randomfloat_arr)}')\n\n# Computes the Square root of the elements; sqrt of negative number gives nan\nprint(f'\\nSquare root = \\n{np.sqrt(np.abs((randomint_arr)))}')\n\n# Computes the Square of the elements\nprint(f'\\nSquare = \\n{np.square(randomint_arr)}')\n\n# Calculate the exponential of all elements in the input array.\nprint(f'\\nExponential = \\n{np.exp(randomint_arr)}')\n\n# Calculate 2**p for all p in the input array.\nprint(f'\\n 2**p = \\n{np.exp2(np.array([1,2,3,4]))}')\n\n# Return the natural logarithm of the input array, element-wise.\nprint(f'\\nlog = \\n{np.log(np.abs(randomint_arr))}')\n\n# Return the base 10 logarithm of the input array, element-wise.\nprint(f'\\nlog10 =\\n {np.log10(np.abs(randomint_arr))}')\n\n# Returns the Base-2 logarithm of x.\nprint(f'\\nlog2=\\n {np.log2(np.abs(randomint_arr))}')\n\n# Returns the natural logarithm of one plus the input array, element-wise.\nprint(f'\\nlog1p = \\n{np.log1p(np.abs(randomint_arr))}')\n\n# Returns an element-wise indication of the sign of a number.\nprint(f'\\nSign of array elements =\\n {np.sign(randomint_arr)}')\n\n# Return the ceiling of the input, element-wise.\nprint(f'\\n Ceiling of elements in array =\\n {np.ceil(randomfloat_arr)}')\n\n# Return the floor of the input, element-wise.\nprint(f'\\n Floor of elements in array =\\n {np.floor(randomfloat_arr)}')\n\n# Returns the Trigonometric sine, element-wise.\nprint(f'\\nsin(array) =\\n {np.sin(randomint_arr)}')\n\n# Returns the Hyperbolic sine, element-wise.\nprint(f'\\nsinh(array) =\\n {np.sinh(randomint_arr)}')\n\n# Returns the Inverse sine, element-wise; \nprint(f'\\narcsin(array) =\\n {np.arcsin(np.array([-1, 1, 0]))}')\n\n# Returns the Trigonometric cosine, element-wise.\nprint(f'\\ncos(array) =\\n {np.cos(randomint_arr)}')\n\n# Returns the Hyperbolic cosine, element-wise.\nprint(f'\\ncosh(array) =\\n {np.cosh(randomint_arr)}')\n\n# Returns the Inverse cosine, element-wise; \nprint(f'\\narccos(array) =\\n {np.arccos(np.array([-1, 1, 0]))}')\n\n# Returns the Trigonometric sine, element-wise.\nprint(f'\\ntan(array) =\\n {np.tan(randomint_arr)}')\n\n# Returns the Hyperbolic tan, element-wise.\nprint(f'\\ntanh(array) =\\n {np.tanh(randomint_arr)}')\n\n# Returns the Inverse tan, element-wise; \nprint(f'\\narctan(array) =\\n {np.arctan(np.array([-1, 1, 0]))}')\n\n\n\n# Creating an array with nan and inf\narr_naninf = np.array([[np.inf,np.nan,np.NaN],\n [np.NAN,33,0],\n [5/np.inf,np.inf*np.nan,np.inf/np.inf]])\n\nprint(f'\\nOriginal array = \\n{arr_naninf}')\n\n# Test element-wise for NaN and return result as a boolean array.\nprint(f'\\n Boolean array checking for nan =\\n {np.isnan(arr_naninf)}')\n\n# Test element-wise for inf and return result as a boolean array.\nprint(f'\\n Boolean array checking for inf =\\n {np.isinf(arr_naninf)}')\n\n# Test element-wise for finiteness (not infinity or not Not a Number).\nprint(f'\\n Boolean array checking for finiteness =\\n {np.isfinite(arr_naninf)}')\n\n# Some concepts regarding NaN and inf\n\n# nan is never equal to nan; result of nan==nan is always false\nprint(\"nan==nan ? {}\".format(np.nan==np.nan))\n\n# inf is equal to inf;\nprint(\"inf==inf ? {}\".format(np.inf==np.inf))\n\n# np.any on NaN, positive infinity and negative infinity evaluate to True \nprint(f\"np.any(np.NaN) is {np.any(np.NaN)}\")\nprint(f\"np.any(+np.inf) is {np.any(+np.inf)}\")\nprint(f\"np.any(-np.inf) is {np.any(-np.inf)}\")\n\n# np.all is True if all elements over the axis chosen in True\n# np.all performs a logical AND between elements on the axis chosen\nprint(f\"\\nnp.all(arr_naninf,axis=0) = \\n{np.all(arr_naninf,axis=0)}\")\nprint(f\"\\narr_naninf.all(axis=1) = \\n{arr_naninf.all(axis=1)}\")\n\n\n\n# Binary universal functions\n\"\"\"\nSince these operators always result in a boolean array, we can use \nthese ufuncs to do element-wise comparisons over arrays.\nWe can use the operators or their equivalent ufunc for \naccomplishing the task.\nFor instance, Operator \"+\" is same as \"np.add\".\n\"\"\"\n# Arrays to demonstrate binary ufuncs that utilize mathematical operations\narr_x = np.round(np.random.randn(2,3,4),2)\narr_y = np.random.randint(10,size=(2,3,4))\n\n# Mathematical Operators\n# Add arguments element-wise.\nprint(f'\\nSum = \\n{np.add(arr_x,arr_y)}')\nprint(f'\\nSum = \\n{arr_x+arr_y}')\n\n# Subtracts arguments element-wise.\nprint(f'\\nDifference = \\n{np.subtract(arr_x,arr_y)}')\nprint(f'\\nDifference = \\n{arr_x-arr_y}')\n\n# Multiply arguments element-wise.\nprint(f'\\nProduct = \\n{np.multiply(arr_x,arr_y)}')\nprint(f'\\nProduct = \\n{arr_x*arr_y}')\n\n# Returns a true division of the inputs, element-wise.\nprint(f'\\n Result of True Divison = \\n{np.divide(arr_x,arr_y)}')\nprint(f'\\n Result of True Divison = \\n{np.true_divide(arr_x,arr_y)}')\nprint(f'\\n Result of True Divison = \\n{arr_x/arr_y}')\n\n# Return element-wise remainder of division.\nprint(f'\\n Remainder of True Divison = \\n{np.mod(arr_x,arr_y)}')\nprint(f'\\n Remainder of True Divison = \\n{np.remainder(arr_x,arr_y)}')\nprint(f'\\n Remainder of True Divison = \\n{arr_x%arr_y}')\n\n# Return element-wise quotient and remainder simultaneously.\n# print(f'\\n Quotient, Remainder = \\n{np.divmod(arr_x,arr_y)}')\n\n# Return the largest integer smaller or equal to the division of the inputs. \nprint(f'\\n Result of Floor Divison = \\n{arr_x//arr_y}')\nprint(f'\\n Result of Floor Divison = \\n{np.floor_divide(arr_x,arr_y)}')\n\n# First array elements raised to powers from second array, element-wise.\nprint(f'\\n arr_y to the power of arr_x = \\n{np.power(arr_y,arr_x)}')\nprint(f'\\n arr_y to the power of arr_x = \\n{arr_y**arr_x}')\n\n# Element-wise maximum of array elements.\nprint(f'\\nmaximum of arrays = \\n{np.maximum(arr_y,arr_x)}')\n\n# Element-wise minimum of array elements.\nprint(f'\\nminimum of arrays = \\n{np.minimum(arr_y,arr_x)}')\n\n# Change the sign of x1 to that of x2, element-wise.\nprint(f'\\n Changes sign of array 1 to that of 2 = \\n{np.copysign(arr_x,arr_y)}')\n\n\n\n\n# Comparison Operators\n\"\"\"\nComparison operators discussed here include :\nequal, less_equal, less, greater_equal, greater\narray_equiv, array_equal\n\"\"\"\n# Arrays to demonstrate binary ufuncs that utilize comparison operations\narr_x1 = np.arange(10)\narr_x2 = np.array([0,1,5,3,2,5,6,8,8,9])\narr_x3 = np.tile(arr_x1,(3,4,1))\n\n\n# Return (x1 == x2) element-wise; x1 and x2 need not have same datatype\n# x1 and x2 are arrays\nprint(f'\\n Boolean array checking for equality = \\n{np.equal(arr_x1,arr_x2)}')\nprint(f'\\n Boolean array checking for equality = \\n{arr_x1==arr_x2}')\n# x1 is of \"int\" type and x2 is an array\nprint(f'\\n Boolean array checking for equality = \\n{8==arr_x2}')\nprint(f'\\n Boolean array checking for equality = \\n{np.equal(8,arr_x2)}')\n\n# Return the truth value of (x1 =< x2) element-wise.\n# x1 and x2 are arrays\nprint(f'\\n Boolean array checking if 1st array =< 2nd array = \\n{np.less_equal(arr_x1,arr_x2)}')\nprint(f'\\n Boolean array checking if 1st array =< 2nd array = \\n{arr_x1<=arr_x2}')\n# x1 is an array and x2 is of \"int\" type \nprint(f'\\n Boolean array checking if 1st array =< 2nd element = \\n{np.less_equal(arr_x2,5)}')\nprint(f'\\n Boolean array checking if 1st array =< 2nd element = \\n{arr_x2<=5}')\n\n# Return the truth value of (x1 < x2) element-wise.\n# x1 and x2 are arrays\nprint(f'\\n Boolean array checking if 1st array < 2nd array = \\n{np.less(arr_x1,arr_x2)}')\nprint(f'\\n Boolean array checking if 1st array < 2nd array = \\n{arr_x1= x2) element-wise.\n# x1 and x2 are arrays\nprint(f'\\n Boolean array checking if 1st array >= 2nd array = \\n{np.greater_equal(arr_x1,arr_x2)}')\nprint(f'\\n Boolean array checking if 1st array >= 2nd array = \\n{arr_x1>=arr_x2}')\n# x1 is an array and x2 is of \"int\" type \nprint(f'\\n Boolean array checking if 1st array >= 2nd element = \\n{np.greater_equal(arr_x2,5)}')\nprint(f'\\n Boolean array checking if 1st array >= 2nd element = \\n{arr_x2>=5}')\n\n# Return the truth value of (x1 > x2) element-wise.\n# x1 and x2 are arrays\nprint(f'\\n Boolean array checking if 1st array > 2nd array = \\n{np.greater(arr_x1,arr_x2)}')\nprint(f'\\n Boolean array checking if 1st array > 2nd array = \\n{arr_x1>arr_x2}')\n# x1 is an array and x2 is of \"int\" type \nprint(f'\\n Boolean array checking if 1st array > 2nd element = \\n{np.greater(arr_x2,5)}')\nprint(f'\\n Boolean array checking if 1st array > 2nd element = \\n{arr_x2>5}')\n\n# Returns True if input arrays are shape consistent and all elements equal.\nprint(f'\\n Consistency in Shape and elements :{np.array_equiv(arr_x1,arr_x2)}')\n# Returns True even if one of the arrays are broadcastable\nprint(f'\\n Consistency in Shape and elements :{np.array_equiv(arr_x1,arr_x3)}')\n\n# True if two arrays have the same shape and elements, False otherwise.\nprint(f'\\n Equality in Shape and elements :{np.array_equal(arr_x1,arr_x2)}')\n# Returns False even if one of them is broadcastable \nprint(f'\\n Equality in Shape and elements :{np.array_equal(arr_x1,arr_x3)}')\n\n\n\n# Logical Operands - Element-wise \n# Compute the truth value of x1 XOR x2, element-wise; True only when one of the conditions is True\nprint(f'\\n Boolean array checking for arr_x2 is either 5 or 8 : {np.logical_xor(arr_x2==5,arr_x2==8)}')\n\n# Compute the truth value of x1 AND x2 element-wise; both conditions should hold \nprint(f'\\n Boolean array checking for 1<= arr_x1 <=5 : \\n{np.logical_and(arr_x1>=1,arr_x2<=5)}')\n\n# Compute the truth value of x1 OR x2 element-wise; atleast one of the conditions should hold\nprint(f'\\n Boolean array checking for elements in arr_x2>5 or arr_x2==0 : \\n{np.logical_or(arr_x2==0,arr_x2>5)}')\n\n# Compute the truth value of x1 NOT x2 element-wise.\nprint(f'\\n Boolean array returning NOT(array): \\n{np.logical_not(arr_x2==0)}')\n\n\n\n\n\n# ufunc special methods\n\"\"\"\nAll binary ufuncs support four methods for performing specialized functions.\n>> reduce\n>> accumulate\n>> reduceat\n>> outer\n\"\"\"\n\n# Array creation\narr_multidim = np.random.randint(9,size=(2,4,2,6))\n\n# Reduces array’s dimension by one, by applying ufunc along one axis.\nnp.add.reduce(arr_multidim,axis=2,initial=10)\n# Keyword \"initial\" lets you initialize the \n\n# Accumulate the result of applying the operator to all elements.\nnp.add.accumulate(arr_multidim,axis=2)\n\n# Performs a (local) reduce with specified slices over a single axis;\n\"\"\"\nnp.ufunc.reduceat : Reduces contiguous slices of data to produce aggregated array\nFormat : np.ufunc.reduceat(array,indices,axis,dtype,none)\n\nFor example : For i in range(length(indices)),reductions are performed on the contiguous slices of data\ni < i+1 ; slice is i:(i+1) where (i+1) is a exclusive outerbound\ni >= i+1; slice is i\ni >= length(array) or i<0; raises an error\n\"\"\"\nnp.add.reduceat(arr_multidim,[0,4,5,2,4,1],axis=3)\n# Slices : [0:4],[4:5],[5],[2:4],[4],[1+]'\n\n\n# Apply the ufunc operation to all pairs for every a in A and b in B\n\"\"\"\nnp.ufunc.outer : Applies ufunc operation to every pair; Resulting array has shape A.shape + B.shape\nFormat : np.ufunc.outer(array_A,arr_B) \nIf shape of array A is (x,y) and B is (l,m,n) ; resulting array will have shape (x,y,l,m,n)\n\"\"\"\nnp.add.outer(arr_multidim[0,0,0],arr_multidim[0,1])\n# Shape of resulting array is (6,2,6)\n\n\n\n# Broadcasting\n\"\"\"\nBroadcasting is a set of rules for applying binary UFuncs on arrays of different sizes.\n\nRules of Broadcasting : \n\n1. Rule 1 : If the 2 arrays differ in dimensions, the shape of the one with fewer dimensions is padded with 1s on its leading side\n2. Rule 2 : If the shape of the 2 arrays does not match in any dimension, tha array with shape equal to 1 is stretched to match the other shape\n3. Rule 3 : If neither sizes match in any dimension nor is 1, then an error is raised\n\"\"\"\n\narr_brdcst1 = np.random.randint(40,size=(2,4,2,1))\narr_brdcst2 = np.random.randint(20,size=(2,3))\narr_brdcst3 = np.random.randint(20,size=(2,3,5))\n\narr_viable = arr_brdcst1 + arr_brdcst2 \n# Rule 1 : Smaller array arr_brdcst2 padded with 1s on left making its dimensions (1,1,2,3)\n# Rule 2 : Due to dimension mismatch, both arr_brdcst1 and arr_brdcst2 are stretched/broadcasted \narr_viable.shape\n# Forms an output array of dimensions (2,4,2,3)\n\n\narr_error_brdcst = arr_brdcst1 + arr_brdcst3\n# Raises an error : operands could not be broadcast together with shapes (2,4,2,1) (2,3,5) \n", "meta": {"hexsha": "c42d2950a4ba8042366b4c8f0777ce873c263db0", "size": 13807, "ext": "py", "lang": "Python", "max_stars_repo_path": "pyFiles/NumPyCodeFiles_Vectorized Computations & Broadcasting.py", "max_stars_repo_name": "prabhupavitra/NumPy-Guide-for-Data-Science", "max_stars_repo_head_hexsha": "ee9e82c6c276da6acfb243e90b6dad55c7bc4415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-16T01:54:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T14:56:53.000Z", "max_issues_repo_path": "pyFiles/NumPyCodeFiles_Vectorized Computations & Broadcasting.py", "max_issues_repo_name": "prabhupavitra/NumPy-Guide-for-Data-Science", "max_issues_repo_head_hexsha": "ee9e82c6c276da6acfb243e90b6dad55c7bc4415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyFiles/NumPyCodeFiles_Vectorized Computations & Broadcasting.py", "max_forks_repo_name": "prabhupavitra/NumPy-Guide-for-Data-Science", "max_forks_repo_head_hexsha": "ee9e82c6c276da6acfb243e90b6dad55c7bc4415", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-23T11:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T11:55:56.000Z", "avg_line_length": 40.0202898551, "max_line_length": 143, "alphanum_fraction": 0.7172448758, "include": true, "reason": "import numpy", "num_tokens": 4099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9822877054447312, "lm_q2_score": 0.9407897529939848, "lm_q1q2_score": 0.9241262077743768}} {"text": "f = lambda x: 0.1*x**5 - 0.2*x**3 + 0.1*x - 0.2\n\nh = 0.05 # Step size, equal differences of x, ∆x\n# h = 0.01 # Smaller step size gives less error\nx = 0.1 # Find derivatives of f(x) at point x\n\n## xi = x, x[i+1] = x+h, x[i+2] = x+2*h, x[i-2] = x-2*h\n\n# Forward Differences Approximation:\ndff1 = (f(x+h) - f(x))/h\ndff2 = (f(x+2*h) - 2*f(x+h) + f(x))/h**2\nprint('Forward Differences Approximation:')\nprint('f\\' (', x, ') = %f' % dff1)\nprint('f\\'\\'(', x, ') = %f' % dff2)\n\n# Central Differences Approximation:\ndfc1 = (f(x+h) - f(x-h))/(2*h)\ndfc2 = (f(x+h) - 2*f(x) + f(x-h))/h**2\nprint('Central Differences Approximation:')\nprint('f\\' (', x, ') = %f' % dfc1)\nprint('f\\'\\'(', x, ') = %f' % dfc2)\n\n# Backward Differences Approximation:\ndfb1 = (f(x) - f(x-h))/h\ndfb2 = (f(x) - 2*f(x-h) + f(x-2*h))/h**2\nprint('Backward Differences Approximation:')\nprint('f\\' (', x, ') = %f' % dfb1)\nprint('f\\'\\'(', x, ') = %f' % dfb2)\n\n# Analytical Differentiation:\ndfa1 = lambda x: 0.5*x**4 - 0.6*x**2 + 0.1\ndfa2 = lambda x: 2.0*x**3 - 1.2*x\nprint('Analytical Differentiation:')\nprint('f\\' (', x, ') = %f' % dfa1(x))\nprint('f\\'\\'(', x, ') = %f' % dfa2(x))\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~ Plotting the function ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nfrom numpy import linspace\nfrom matplotlib.pyplot import plot, xlabel, ylabel, legend, grid, show\n\nh = 0.01\nX = linspace(0, 1, 11) # Divides from 0 to 1 into 11 points\n\n# Central Differences Approximation:\nDFC1 = (f(X+h) - f(X-h))/(2*h)\nDFC2 = (f(X+h) - 2*f(X) + f(X-h))/h**2\n\n# pyplot.\nplot(X,f(X),'-k', X,DFC1,'--b', X,DFC2,'-.r')\nxlabel('x')\nylabel('y, y\\', y\\'\\'')\nlegend(['f(x)', 'f\\'(x)', 'f\\'\\'(x)'])\ngrid()\nshow()\n\n\n\"\"\"\nf'(x) = df(x)/dx = lim x→0 (∆f(x)/∆x)\nf'(x) ≈ (f(x+∆x)-f(x))/∆x \nf'(xi) ≈ (f(x[i+1])-f(xi))/h where x = xi, x+∆x = x[i+1], ∆x = h\n\nTaylor's series expansion of f(x):\nf(x) = f(a) + f'(a)/1! (x-a) + f''(a)/2! (x-a)^2 + f'''(a)/3! (x-a)^3 + ...\n\nThe expansion of f(x[i+1]) will be: x = x[i+1], a = xi, x-a = x[i+1]-xi = h\nf(x[i+1]) = f(xi) + f'(xi).h + f''(xi).h^2 / 2! + f'''(xi).h^3 / 3! + ...\nf'(xi) = (f(x[i+1]) - f(xi))/h - f''(xi).h / 2! - f'''(xi).h^2 / 3! + ...\nBy omitting the terms containing second and higher derivatives:\nf'(xi) = (f(x[i+1]) - f(xi))/h + O(h) ; O(h) is the error from truncation\n\n(a) Forward Finite Differences: Error O(h)\nf' (xi) = (f(x[i+1]) - f(xi))/h\nf'' (xi) = (f(x[i+2]) - 2f(x[i+1]) + f(xi))/h^2\nf''' (xi) = (f(x[i+3]) - 3f(x[i+2]) + 3f(x[i+1]) - f(xi))/h^3\nf''''(xi) = (f(x[i+4]) - 4f(x[i+3]) + 6f(x[i+2]) - 4f(x[i+1]) + f(xi))/h^4\n\n(b) Central Finite Differences: Error O(h^2)\nf' (xi) = (f(x[i+1]) - f(x[i-1]))/2h\nf'' (xi) = (f(x[i+2]) - 2f(xi) + f(x[i-1]))/h^2\nf''' (xi) = (f(x[i+2]) - 2f(x[i+1]) + 2f(x[i-1]) - f(x[i-2]))/2h^3\nf''''(xi) = (f(x[i+2]) - 4f(x[i+1]) + 6f(xi) - 4f(x[i-1]) + f(x[i-2]))/h^4\n\n(c) Backward Finite Differences: Error O(h)\nf' (xi) = (f(xi) - f(x[i-1]))/h\nf'' (xi) = (f(xi) - 2f(x[i-1]) + f(x[i-2]))/h^2\nf''' (xi) = (f(xi) - 3f(x[i-1]) + 3f(x[i-2]) - f(x[i-3]))/h^3\nf''''(xi) = (f(xi) - 4f(x[i-1]) + 6f(x[i-2]) - 4f(x[i-3]) + f(x[i-4]))/h^4\n\n\"\"\"\n", "meta": {"hexsha": "8fde92a883137402b1d6228538c59972e78bfec9", "size": 3100, "ext": "py", "lang": "Python", "max_stars_repo_path": "3. Numerical Differentiation/1. Finite Differences Approximations or Methods.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3. Numerical Differentiation/1. Finite Differences Approximations or Methods.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3. Numerical Differentiation/1. Finite Differences Approximations or Methods.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6956521739, "max_line_length": 76, "alphanum_fraction": 0.4767741935, "include": true, "reason": "from numpy", "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9828232869627774, "lm_q2_score": 0.939913356558485, "lm_q1q2_score": 0.9237687345530272}} {"text": "import numpy as np \n\ndef euclidean_distances(X, Y):\n \"\"\"Compute pairwise Euclidean distance between the rows of two matrices X (shape MxK) \n and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n the Euclidean distance between two rows.\n \n Arguments:\n X {np.ndarray} -- First matrix, containing M examples with K features each.\n Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n Returns:\n D {np.ndarray}: MxN matrix with Euclidean distances between rows of X and rows of Y.\n \"\"\"\n\n M = X.shape[0]\n N = Y.shape[0]\n D = np.zeros([M, N])\n\n for i in range(M):\n for j in range(N):\n D[i, j] = np.sqrt(np.dot(X[i] - Y[j], X[i] - Y[j]))\n\n return D\n\n\n\n\ndef manhattan_distances(X, Y):\n \"\"\"Compute pairwise Manhattan distance between the rows of two matrices X (shape MxK) \n and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n the Manhattan distance between two rows.\n \n Arguments:\n X {np.ndarray} -- First matrix, containing M examples with K features each.\n Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n Returns:\n D {np.ndarray}: MxN matrix with Manhattan distances between rows of X and rows of Y.\n \"\"\"\n\n\n M = X.shape[0]\n N = Y.shape[0]\n D = np.zeros([M, N])\n\n for i in range(M):\n for j in range(N):\n temp = np.abs(X[i] - Y[j])\n D[i, j] = np.sum(temp)\n\n return D\n\n\ndef cosine_distances(X, Y):\n \"\"\"Compute Cosine distance between the rows of two matrices X (shape MxK) \n and Y (shape NxK). The output of this function is a matrix of shape MxN containing\n the Cosine distance between two rows.\n \n Arguments:\n X {np.ndarray} -- First matrix, containing M examples with K features each.\n Y {np.ndarray} -- Second matrix, containing N examples with K features each.\n\n Returns:\n D {np.ndarray}: MxN matrix with Cosine distances between rows of X and rows of Y.\n \"\"\"\n\n M = X.shape[0]\n N = Y.shape[0]\n D = np.zeros([M, N])\n\n for i in range(M):\n for j in range(N):\n n_1 = np.sqrt(np.dot(X[i], X[i]))\n n_2 = np.sqrt(np.dot(Y[j], Y[j]))\n # This yield the cosine value of the two vectors, which range from 1 to -1\n D[i, j] = np.dot(X[i], Y[j]) / (n_1 * n_2)\n\n # Larger value (closer to 1) means the two vectors have similar direction, so they\n # should have smaller distance\n return 1 - D\n", "meta": {"hexsha": "900825eb1f2bad37fa5e0f75b22b89b887145924", "size": 2566, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/distances.py", "max_stars_repo_name": "jinyangpeter/nucs349_final", "max_stars_repo_head_hexsha": "f31c6d1981851b17c5f596176aa81d79047790c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.py", "max_issues_repo_name": "jinyangpeter/nucs349_final", "max_issues_repo_head_hexsha": "f31c6d1981851b17c5f596176aa81d79047790c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.py", "max_forks_repo_name": "jinyangpeter/nucs349_final", "max_forks_repo_head_hexsha": "f31c6d1981851b17c5f596176aa81d79047790c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2926829268, "max_line_length": 92, "alphanum_fraction": 0.6122369447, "include": true, "reason": "import numpy", "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105238756898, "lm_q2_score": 0.9458012701768145, "lm_q1q2_score": 0.9233957335686186}} {"text": "print('*'*15+'Plain numpy implementation of PCA'+'*'*15)\n#Written using only numpy\nfrom numpy import array,mean,cov\nfrom numpy.linalg import eig\nfrom sklearn.decomposition._pca import PCA\n\n#define matrix\nprint(\"\\n\")\nA = array([[1,2],[3,4],[5,6]])\nprint(\"Initial Martix = {} \\n\".format(A))\n\n#Calculate mean\nM = mean(A.T,axis = 1)\nprint(\"Mean of the matrix = {} \\n\".format(M))\n\n#Scale columns by subtracting column means\nC = A - M\nprint(\"Column scaling applied over the matrix = {} \\n\".format(C))\n\n#Calculate covariance\nV = cov(C.T)\nprint(\"Covariance of the matrix = {} \\n\".format(V))\n\nvalues,vectors = eig(V)\nprint(\"Eigen Vectors = {} \\n\".format(vectors))\nprint(\"Eigen values = {} \\n\".format(values))\n\nP = vectors.T.dot(C.T)\nprint(\"Matrix after applying PCA = {} \\n\".format(P.T))\n\n#Scikit learn Verifcation of the above result\nprint('*'*15+'Verification of the above result using sklearn'+'*'*15)\n\nfrom numpy import array\nfrom sklearn.decomposition import PCA\n# define a matrix\nA = array([[1, 2], [3, 4], [5, 6]])\nprint(A)\n# create the PCA instance\npca = PCA(2)\n# fit on data\npca.fit(A)\n# access values and vectors\nprint(pca.components_)\nprint(pca.explained_variance_)\n# transform data\nB = pca.transform(A)\nprint(B)\n\"\"\"\n***************Plain numpy implementation of PCA***************\nInitial Martix = [[1 2]\n [3 4]\n [5 6]]\nMean of the matrix = [3. 4.]\nColumn scaling applied over the matrix = [[-2. -2.]\n [ 0. 0.]\n [ 2. 2.]]\nCovariance of the matrix = [[4. 4.]\n [4. 4.]]\nEigen Vectors = [[ 0.70710678 -0.70710678]\n [ 0.70710678 0.70710678]]\nEigen values = [8. 0.]\nMatrix after applying PCA = [[-2.82842712 0. ]\n [ 0. 0. ]\n [ 2.82842712 0. ]]\n***************Verification of the above result***************\n[[1 2]\n [3 4]\n [5 6]]\n[[ 0.70710678 0.70710678]\n [-0.70710678 0.70710678]]\n[8. 0.]\n[[-2.82842712e+00 -2.22044605e-16]\n [ 0.00000000e+00 0.00000000e+00]\n [ 2.82842712e+00 2.22044605e-16]]\n\"\"\"", "meta": {"hexsha": "c39ddd064c6bf7197c054d18cba702cf19c0574b", "size": 1933, "ext": "py", "lang": "Python", "max_stars_repo_path": "ML/PCA/simple-pca.py", "max_stars_repo_name": "sihaanssr/semVI", "max_stars_repo_head_hexsha": "3d7a773eb533e2f05249839d3730c8b4cbefca15", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ML/PCA/simple-pca.py", "max_issues_repo_name": "sihaanssr/semVI", "max_issues_repo_head_hexsha": "3d7a773eb533e2f05249839d3730c8b4cbefca15", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-22T13:17:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-23T11:15:45.000Z", "max_forks_repo_path": "ML/PCA/simple-pca.py", "max_forks_repo_name": "sihaanssr/semVI", "max_forks_repo_head_hexsha": "3d7a773eb533e2f05249839d3730c8b4cbefca15", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4342105263, "max_line_length": 69, "alphanum_fraction": 0.6311433006, "include": true, "reason": "from numpy", "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407160384083, "lm_q2_score": 0.9473810466522862, "lm_q1q2_score": 0.9220298082050877}} {"text": "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n###### generate some data ###########\nX = np.linspace(-1, 1, 100)[:, np.newaxis]\nnp.random.shuffle(X) # randomize the data\n# Y = 1 * X**3 + 0.5 * X**2 + 1 + np.random.normal(0, 0.01, (100, 1)) #曲線\nY = 3 * X + 2 + np.random.normal(0, 0.05, (100, 1)) # 線性\nX_train, Y_train = X[:70], Y[:70] # train 前 60 data points\nX_test, Y_test = X[70:], Y[70:]\n\n\ndim_input = 1\ndim_output = 1\n########### Linear Regression by TensorFlow (GradientDescent) ###############\nxs = tf.placeholder(tf.float32, [None, dim_input], name='x_input')\nys = tf.placeholder(tf.float32, [None, dim_output], name='y_output')\n# prediction = xs * w + b\nw = tf.Variable(tf.random_normal([dim_input, dim_output]))\nb = tf.Variable(tf.zeros([1, dim_output]) + 1,)\nprediction = tf.matmul(xs, w) + b\n# loss function (prediction and real target)\nloss = tf.reduce_mean(tf.reduce_sum(\n tf.square(prediction-ys), reduction_indices=[1]), name='Loss')\n# optimal: find the Weights and biases\ntrain_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n#############################################\n\n######## Learning #####################\nmse = np.array([])\nfor i in range(1000):\n # training\n sess.run(train_step, feed_dict={xs: X_train, ys: Y_train})\n y_pre = sess.run(prediction, feed_dict={xs: X_test})\n mse = np.append(mse, np.mean(np.sqrt(np.sum(np.square(Y_test-y_pre)))))\n if i >= 1:\n if abs(mse[i]-mse[i-1]) < np.spacing(1):\n break\n print('Iternation' + str(i+1) + ': MSE=' + str(mse[i]))\nmse_tf = mse[-1]\nplt.plot(mse)\nplt.xlabel('Iternation time')\nplt.ylabel('MSE')\nplt.title('MSE')\nplt.show()\n\n####### Least square error Regression by closedform ########\n#最小平方法即是將\n# beta=(X^TX)^-1 X^T Y\ndef Train_LSE_Regression(x, y):\n tmp1 = np.matmul(np.transpose(x), x)\n tmp1 = np.linalg.pinv(tmp1)\n tmp2 = np.matmul(np.transpose(y), x)\n Weight = np.matmul(tmp1, np.transpose(tmp2))\n return Weight\n\n\nn_train = np.size(X_train, 0)\nn_test = np.size(X_test, 0)\nX_input_train = np.concatenate((X_train, np.ones([n_train, 1])), axis=1)\nWeight_LSE = Train_LSE_Regression(X_input_train, Y_train)\n\nX_input_test = np.concatenate((X_test, np.ones([n_test, 1])), axis=1)\ny_pre_LSE = np.matmul(X_input_test, Weight_LSE)\nmse_LSE = np.mean(np.sqrt(np.sum(np.square(Y_test-y_pre))))\n\n# compared the weight between these two methods\nprint('TF (GD) Weights:' + str(sess.run(w)) + str(sess.run(b)))\nprint('TF (GD) MSE:' + str(mse_tf))\nprint('LSE Weights:' + str(Weight_LSE[0]) + str(Weight_LSE[1]))\nprint('LSE MSE:' + str(mse_LSE))\n\n### plot generated data######\nfig = plt.figure()\nax = fig.add_subplot(2, 1, 1)\nax.scatter(X_train, Y_train)\nax.set_xlabel('Input data')\nax.set_ylabel('Target result')\nax.set_title('Train data')\nplt.ion() # can hold on\nax = fig.add_subplot(2, 1, 2)\nax.scatter(X_test, Y_test)\nax.scatter(X_test, y_pre, color=\"r\")\nax.scatter(X_test, y_pre_LSE, color=\"b\")\nax.set_xlabel('Input data')\nax.set_ylabel('Target result')\nax.set_title('Test data')\nplt.show()\n\n'''\n結論:\n從結果可以發現,梯度法執行到收斂後找到的答案跟唯一解找出來的答案基本上一致。\n雖然唯一解很快,只需要矩陣運算計算一組即可以得到答案\n但因為唯一解在高維度低樣本數時可能會有共變異數矩陣(covariance matrix)奇異(singular)的情況出現\n這時候可能會造成估計錯誤,造成不良的結果\n所以最好實際上在算的時候,還是用梯度法去執行Regression。\n\n我的理解:\n用最小平方法即是找到圖形中微分等於零的點,但因為微分等於零有可能是局部較佳解,也有可能是平坦的面,所以用梯度。\n梯度下降是找偏微分(梯度),wb減去其值。而最小平方法是令梯度等於零(最低、最高點),找出wb\n'''", "meta": {"hexsha": "3a36794c14a26e22d321d4f3930f8ba861d2cc54", "size": 3439, "ext": "py", "lang": "Python", "max_stars_repo_path": "attachments/LinearRegression.py", "max_stars_repo_name": "BradXiao/bradxiao.github.io", "max_stars_repo_head_hexsha": "2b9d30999d165a3f39d1ae532e8219fd99177fd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "attachments/LinearRegression.py", "max_issues_repo_name": "BradXiao/bradxiao.github.io", "max_issues_repo_head_hexsha": "2b9d30999d165a3f39d1ae532e8219fd99177fd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2020-04-23T15:00:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T22:09:43.000Z", "max_forks_repo_path": "attachments/LinearRegression.py", "max_forks_repo_name": "BradXiao/BradXiao.github.io", "max_forks_repo_head_hexsha": "2b9d30999d165a3f39d1ae532e8219fd99177fd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0673076923, "max_line_length": 78, "alphanum_fraction": 0.6667635941, "include": true, "reason": "import numpy", "num_tokens": 1297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9773707999669627, "lm_q2_score": 0.9425067272555727, "lm_q1q2_score": 0.9211785539920231}} {"text": "\"\"\"\ndemo_nonlinear_data_fitting.py\n\nFit a model A * sin(W * t + phi) to the data f(X, ti) = yi to find A, W, and phi\nm = number of data points\n\nSolve a system of non-linear equations f(X, ti) - yi = 0:\n x1 * sin(x2 * t + x3) - y = 0, where X = [x1 = A, x2 = W, x3 = phi].T, t = [t1, t2, ..., tm].T and y = [y1, y2, ..., ym].T\n\nMinimize the following objective function: (f(X, t) - y).T @ (f(X, t) - y)\n\nLevenberg - Marquardt algorithm\n General algorithm for any f(X) function. Requires residuals and jacobian.\n X0 converges to X* for any X0.\n \nNaive random walk algorithm\n General algorithm for any f(X) function. Requires only residuals.\n X0 converges to X* for any X0.\n \nSimulated annealing algorithm\n General algorithm for any f(X) function. Requires only residuals.\n X0 converges to X* for any X0.\n \nParticle swarm optimization algorithm\n General algorithm for any f(X) function. Requires only residuals.\n X0 converges to X* for any X0.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom levenberg_marquardt_algorithm import levenberg_marquardt_algorithm\nfrom naive_random_search_algorithm import naive_random_search_algorithm\nfrom simulated_annealing_algorithm import simulated_annealing_algorithm\nfrom particle_swam_optimization_algorithm import particle_swam_optimization_algorithm\nfrom print_report import print_report\nfrom plot_progress_y import plot_progress_y\nimport time\n\nX = np.array([[0.75], [2.3], [-3]]);\nt = np.arange(0, 20, 0.1);\n# Nonlinear model to fit\nfunc = lambda X : X[0] * np.sin(X[1] * t + X[2]); \n# Plot the curve\nfig = plt.figure();\ny = func(X);\nplt.plot(t, y)\nplt.show()\n\nfunc_residual = lambda X : (X[0] * np.sin(X[1] * t + X[2]) - y).reshape((t.size, 1));\nfunc_jacobian = lambda X : np.array([[-np.sin(X[1] * t + X[2])], [-t * X[0] * np.cos(X[1] * t + X[2])], [-X[0] * np.cos(X[1] * t + X[2])]]).reshape((t.size, X.size));\n# Objective function for naive random walk and simulated annealing algorithms\nfunc_error = lambda X : np.linalg.norm((X[0] * np.sin(X[1] * t + X[2]) - y).reshape((t.size, 1)), axis = 0) ** 2;\n# Objective function for particle swarm optimization algorithm (particles along row dimension, axis = 0)\nfunc_error_ps = lambda X : np.linalg.norm(X[:, [0]] * np.sin(X[:, [1]] * t + X[:, [2]]) - y, axis = 1).reshape((-1, 1)) ** 2;\n\n# Levenberg-Marquardt algorithm\nprint('***********************************************************************');\nprint('Levenberg - Marquardt algorithm');\nN_iter_max = 1000;\ntolerance_x = 10e-6;\ntolerance_y = 10e-8;\nX_lower = np.array([[0], [0], [-5]]); # X lower bound \nX_upper = np.array([[2], [5], [0]]); # X upper bound\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max, 'x_lower' : X_lower, \n 'x_upper' : X_upper};\nX0 = np.array([[0.1], [1], [-2]]);\nstart = time.time();\nX, report = levenberg_marquardt_algorithm(X0, func_residual, func_jacobian, options);\nend = time.time();\nprint_report(func_error, report);\n# Plot path to X* for Y\nalgorithm_name = 'Levenberg - Marquardt algorithm';\nplot_progress_y(algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n');\n\n# Naive random walk algorithm\nprint('***********************************************************************');\nprint('Naive random walk algorithm');\nN_iter_max = 1000;\ntolerance_x = 10e-8;\ntolerance_y = 10e-8;\nX_lower = np.array([[0], [0], [-5]]); # X lower bound \nX_upper = np.array([[2], [5], [0]]); # X upper bound\nalpha = 0.5; # step size\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max, 'x_lower' : X_lower, \n 'x_upper' : X_upper, 'alpha' : alpha};\nX0 = np.array([[0.1], [1], [-2]]); # X0 = X_lower + (X_upper - X_lower) * np.random.rand(X_lower.size, 1); \nstart = time.time();\nX, report = naive_random_search_algorithm(X0, func_error, options);\nend = time.time();\nprint_report(func_error, report);\n# Plot path to X* for Y\nalgorithm_name = 'Naive random walk algorithm';\nplot_progress_y(algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n');\n\n# Simulated annealing algorithm\nprint('***********************************************************************');\nprint('Simulated annealing algorithm');\nN_iter_max = 1000;\ntolerance_x = 10e-8;\ntolerance_y = 10e-8;\nX_lower = np.array([[0], [0], [-5]]); # X lower bound \nX_upper = np.array([[2], [5], [0]]); # X upper bound\nalpha = 1.0; # step size\ngamma = 1.5; # controls temperature decay, gamma > 0\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max, 'x_lower' : X_lower, \n 'x_upper' : X_upper, 'alpha' : alpha, 'gamma' : gamma};\nX0 = np.array([[0.1], [1], [-2]]); # X0 = X_lower + (X_upper - X_lower) * np.random.rand(X_lower.size, 1); \nstart = time.time();\nX, report = simulated_annealing_algorithm(X0, func_error, options);\nend = time.time();\nprint_report(func_error, report);\n# Plot path to X* for Y\nalgorithm_name = 'Simulated annealing algorithm';\nplot_progress_y(algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n');\n\n# Particle swarm optimization algorithm\nprint('***********************************************************************');\nprint('Particle swarm optimization algorithm');\nN_iter_max = 1000;\ntolerance_x = 10e-8;\ntolerance_y = 10e-8;\nX_lower = np.array([[0], [0], [-5]]); # X lower bound \nX_upper = np.array([[2], [5], [0]]); # X upper bound\nd_lower = -1; # direction (aka velocity) lower bound\nd_upper = 1; # direction (aka velocity) upper bound\nN_ps = 10000; # number of particles\nw = 0.9; # inertial constant, w < 1\nc1 = 1.5; # cognitive/independent component, c1 ~ 2\nc2 = 1.5; # social component, c2 ~ 2\nalpha = 1; # step size\noptions = {'tolerance_x' : tolerance_x, 'tolerance_y' : tolerance_y, 'N_iter_max' : N_iter_max, 'x_lower' : X_lower, \n 'x_upper' : X_upper, 'alpha' : alpha, 'd_lower' : d_lower, 'd_upper' : d_upper, 'N_ps' : N_ps, 'w' : w, 'c1' : c1, 'c2' : c2};\nstart = time.time();\nX, report = particle_swam_optimization_algorithm(func_error_ps, options);\nend = time.time();\nprint_report(func_error, report);\n# Plot path to X* for Y\nalgorithm_name = 'Particle swarm optimization algorithm';\nplot_progress_y(algorithm_name, report);\nprint('Elapsed time [s]: %0.5f' % (end - start));\nprint('***********************************************************************\\n');", "meta": {"hexsha": "99175e305e91f74cfd9b97e4031f7f7524add878", "size": 6639, "ext": "py", "lang": "Python", "max_stars_repo_path": "nonlinear_data_fitting/demo_nonlinear_data_fitting.py", "max_stars_repo_name": "almostdutch/numerical-optimization-algorithms", "max_stars_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nonlinear_data_fitting/demo_nonlinear_data_fitting.py", "max_issues_repo_name": "almostdutch/numerical-optimization-algorithms", "max_issues_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-02T10:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T10:23:46.000Z", "max_forks_repo_path": "nonlinear_data_fitting/demo_nonlinear_data_fitting.py", "max_forks_repo_name": "almostdutch/numerical-optimization-algorithms", "max_forks_repo_head_hexsha": "cd6c1306cb04eccce62a74420323bda83058c1d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1632653061, "max_line_length": 166, "alphanum_fraction": 0.6130441332, "include": true, "reason": "import numpy", "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517462851323, "lm_q2_score": 0.9416541585696252, "lm_q1q2_score": 0.9209864941856788}} {"text": "from functools import reduce\n\nimport numpy as np\n\n\n# Dynamic programming solution from CLRS 15.2\ndef matrix_chain_order(p):\n n = len(p) - 1\n m = np.zeros(shape=[n, n])\n s = np.zeros(shape=[n, n])\n for l in range(2, n + 1):\n for i in range(0, n - l + 1):\n j = i + l - 1\n m[i, j] = np.Inf\n for k in range(i, j):\n q = m[i, k] + m[k + 1, j] + p[i] * p[k + 1] * p[j + 1]\n if q < m[i, j]:\n m[i, j] = q\n s[i, j] = k\n m = m.astype(int)\n s = s.astype(int)\n return m, s\n\n# Print the optimal parenthesisation\ndef optimal_parenthesis(s, i, j, print=True):\n if i == j:\n return 'A{}'.format(i + 1)\n else:\n return '({}{})'.format(optimal_parenthesis(s, i, s[i, j]),\n optimal_parenthesis(s, s[i, j] + 1, j))\n\n# \"Dumb\" chain_multiply\ndef chain_multiply(arrays): \n return reduce(np.dot, arrays)\n\n# Recursive chain_multiply using the DP optimal solution\ndef chain_multiply_dp(arrays):\n p = [x.shape[0] for x in arrays]\n p.append(arrays[-1].shape[1])\n m, s = matrix_chain_order(p)\n\n def chain_multiply_dp_aux(i, j):\n if i == j:\n return arrays[i]\n else:\n return np.dot(chain_multiply_dp_aux(i, s[i, j]),\n chain_multiply_dp_aux(s[i, j] + 1, j))\n\n return chain_multiply_dp_aux(0, len(p) - 2)\n\n# To generate a bunch of random arrays for benchmarking\ndef generate_arrays(p):\n rng = np.random.default_rng()\n return [rng.random((dim1, dim2)) for dim1, dim2 in zip(p[:-1], p[1:])]\n\n# Stuff from CLRS\np = [30, 35, 15, 5, 10, 20, 25]\nm, s = matrix_chain_order(p)\nm[0, 5] # min number of scalar multiplications\noptimal_parenthesis(s, 0, 5) # optimal parenthesisation\n\n# Try to do the actual multiplications with random arrays\narrays_random = generate_arrays(p)\n\nprod0 = chain_multiply(arrays_random)\nprod1 = np.linalg.multi_dot(arrays_random)\nprod2 = chain_multiply_dp(arrays_random)\nnp.linalg.norm(prod0 - prod1) # floating point precision\nnp.linalg.norm(prod1 - prod2)\n\n# Increase the dimension for benchmarking\np10 = [x * 10 for x in p]\narrays_random = generate_arrays(p10)\n\n%timeit chain_multiply(arrays_random)\n%timeit np.linalg.multi_dot(arrays_random)\n%timeit chain_multiply_dp(arrays_random)\n\n", "meta": {"hexsha": "25605f81988c980c3175ebfeb18fd1ca8886f186", "size": 2208, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/clrs_chap15/matrix_multiply.py", "max_stars_repo_name": "tvatter/dsa", "max_stars_repo_head_hexsha": "e5ae217e38441d90914a55103e23d86f5821dc2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/clrs_chap15/matrix_multiply.py", "max_issues_repo_name": "tvatter/dsa", "max_issues_repo_head_hexsha": "e5ae217e38441d90914a55103e23d86f5821dc2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/clrs_chap15/matrix_multiply.py", "max_forks_repo_name": "tvatter/dsa", "max_forks_repo_head_hexsha": "e5ae217e38441d90914a55103e23d86f5821dc2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9493670886, "max_line_length": 72, "alphanum_fraction": 0.6449275362, "include": true, "reason": "import numpy", "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307700397332, "lm_q2_score": 0.9465966683169889, "lm_q1q2_score": 0.9208783657558621}} {"text": "import numpy as np\r\nfrom matplotlib import pyplot\r\nimport math\r\n#from mplkit.mplot3d import axes3d\r\n\r\n\r\n# Load the data\r\ndata = np.loadtxt('linear_regression.txt', delimiter = ',')\r\n#separate predictor from target variable\r\nxd = np.c_[np.ones(data.shape[0]), data[:,0]]\r\nyd = np.c_[data[:,1]]\r\nprint(yd.shape)\r\nprint(xd.shape)\r\n\r\n# First appraoch - Normal equation\r\n\r\ndef normalEquation(x,y):\r\n \"\"\"\r\n Parameteres: input variables (Table) , Target vector\r\n Instructions: Complete the code to compute the closed form solution to linear regression and \tsave the result in theta.\r\n Return: coefficinets \r\n \"\"\"\r\n theta=[]\r\n x_t=np.transpose(x)\r\n theta=np.linalg.inv(x_t.dot(x))\r\n theta=theta.dot(x_t)\r\n theta=theta.dot(y)\r\n return theta\r\n\r\n# Iterative Approach - Gradient Descent \r\n\r\n'''\r\nFollowing paramteres need to be set by you - you may need to run your code multiple times to find the best combination \r\n'''\r\ntheta=np.matrix([[0],[0]])\r\ni=1000\r\nr=0.01\r\n\r\ndef gradient_descent(x,y,theta,i,r):\r\n \"\"\"\r\n Paramters: input variable , Target variable, theta, number of iteration, learning_rate\r\n Instructions: Complete the code to compute the iterative solution to linear regression, in each iteration you will \r\n add the cost of the iteration to a an empty list name cost_hisotry and update the theta.\r\n Return: theta, cost_history \r\n \"\"\"\r\n n=float(len(y))\r\n cost_history = []\r\n theta1=[]\r\n theta2=[]\r\n # Your code goes here\r\n x_t=np.transpose(x)\r\n for i in range(0,i):\r\n theta1.append(theta.item(0,0))\r\n theta2.append(theta.item(1,0))\r\n ytrain=x.dot(theta)\r\n ydiff=y-ytrain\r\n cost=(np.transpose(ydiff).dot(ydiff))/(2*n)\r\n cost_history.append(float(cost))\r\n thetagrad=((x_t).dot(ydiff))/n\r\n theta=theta+r*(thetagrad)\r\n return theta, cost_history,theta1,theta2\r\n\r\nprint(gradient_descent(xd,yd,theta,i,r)[0])\r\nprint(normalEquation(xd,yd))\r\n\r\n\r\n# Plot the cost over number of iterations\r\n\r\n#Your plot should be similar to the provided plot\r\n\r\nx=range(0,1000)\r\npyplot.plot(x,gradient_descent(xd,yd,theta,i,r)[1])\r\npyplot.show()\r\n\"\"\"\r\ntheta, cost_history,theta1,theta2=gradient_descent(xd,yd,theta,i,r)\r\n\r\n# Plot the linear regression line for both gradient approach and normal equation in same plot\r\n'''\r\nhints: your x-axis will be your predictor variable and y-axis will be your target variable. plot a\r\nscatter plot and draw the regression line using the theta calculated from both approaches. Your plot\r\nshould be similar to what provided.\r\n'''\r\n\r\n\r\n\r\n# Plot contour plot and 3d plot for the gradient descent approach\r\n\r\n'''\r\nyour plots should be similar to our plots.\r\n\r\n'''\r\n\r\n#pyplot.contour(theta1, theta2, cost_history, colors='black');\r\n\r\n\"\"\"\r\npyplot.plot(xd,yd,'ro')\r\npyplot.plot(xd,xd.dot(normalEquation(xd,yd)))\r\npyplot.plot(xd,xd.dot((gradient_descent(xd,yd,theta,i,r))[0]))\r\npyplot.show()\r\n", "meta": {"hexsha": "15c726edf64b68e33d1f1eb9b9a0176354a54a07", "size": 2926, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression.py", "max_stars_repo_name": "Sivatejareddyseelam/ML_algo", "max_stars_repo_head_hexsha": "1b8510386058b4198af549cda509c564cd301ca9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_regression.py", "max_issues_repo_name": "Sivatejareddyseelam/ML_algo", "max_issues_repo_head_hexsha": "1b8510386058b4198af549cda509c564cd301ca9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression.py", "max_forks_repo_name": "Sivatejareddyseelam/ML_algo", "max_forks_repo_head_hexsha": "1b8510386058b4198af549cda509c564cd301ca9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.26, "max_line_length": 124, "alphanum_fraction": 0.6821599453, "include": true, "reason": "import numpy", "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668734137681, "lm_q2_score": 0.9362850119705769, "lm_q1q2_score": 0.9186518378193433}} {"text": "import scipy.special\nimport numpy as np\nimport matplotlib\n\ndef function(x0):\n return np.sin(x0)\n\ndef function_derivative(x0):\n return np.cos(x0)\n\nx0 = 1.2 ## point that we compute the derivative at (ie d/dx sin(x) at x = x0)\nf0 = function(x0) ## f(x0)\nfp = function_derivative(x0) ## f'(x0) the `p` means 'prime'\nfpp = -function(x0) ## f''(x0)\ni = linspace(-20, 0, 40) ## `linspace` gives a range of values between two end points\n## in this case 40 points, between -20 and 0\nh = 10.0**i ## this is our approx parameter, it is an array of values \n## between 10^(-20) and 10^(0)\n\n# Remember we are using the forward difference formula\nfp_approx = (sin(x0 + h) - f0)/h ## the derivative approximation\n\n# To use the central difference formula\n# Absolute error in 0(h^2) as long as f'''(x) is bounded \n# fp_approx = (sin(x0 + h) - sin(x0 - h))/(2*h)\n\n# To use the backward difference formula\n# fp_approx = (f0 - sin(x0 - h))/h\n\n# Forward difference formula\nerr = absolute(fp - fp_approx) ## the full absolute error\nd_err = h/2*absolute(fpp) ## the formula for the discretization error, derived above\n \nfigure(1, [7, 5]) ## creates a blank figure 7 inches (wide) by 5 inches (height)\nloglog(h, err, '-*') ## makes a plot with a log scale on both the x and y axis\nloglog(h, d_err, 'r-', label=r'$\\frac{h}{2}\\vert f^{\\prime\\prime}(x) \\vert $')\nxlabel('h', fontsize=20) ## puts a label on the x axis\nylabel('absolute error', fontsize=20) ## puts a label on the y axis\nylim(1e-15, 1) ## places limits on the yaxis for our plot\nlegend(fontsize=24); ## creates a figure legend (uses the `label=...` arguments in the plot command)\n \n# notes : For ℎ small but not too small, the absolute error is dominated by the discretization error, \n# ℎ|𝑓″(𝑥)|/2 , which is larger than other sources of error such as roundoff error.\n# Once ℎ<10−8 , the discretization error becomes smaller than the roundoff error, and the roundoff error continues to get larger as ℎ→0 .\n\n\n# Centered Difference Formula\nx0 = 1.2 ## point that we compute the derivative at (ie d/dx sin(x) at x = x0)\nf0 = sin(x0) ## f(x0)\nfp = cos(x0) ## f'(x0) the `p` means 'prime'\nfpp = -sin(x0) ## f''(x0)\nfppp = -cos(x0) ## f'''(x0)\ni = linspace(-20, -1, 40) ## `linspace` gives a range of values between two end points\n## in this case 40 points, between -20 and 0\nh = 10.0**i ## this is our approx parameter, it is an array of values \n## between 10^(-20) and 10^(0)\nfp_approx_q1 = (sin(x0 + h) - sin(x0 - h))/(2*h) ## the derivative approximation\nfp_approx_example = (sin(x0 + h) - f0)/h\nprint(\"Derivative Approximation \" , fp_approx_q1)\n\nerr = absolute(fp - fp_approx_q1) ## the full absolute error\nerr1 = absolute(fp - fp_approx_example)\nprint(\"Absolute Error\", err)\nd_err_q1 = (h**2/6)*absolute(fppp) ## the formula for the discretization error, derived above\nd_err_example = (h/2) * absolute(fpp)\nprint(\"Exact Derivative\",d_err)\n\n\n# Comparison Plots of the two methods\nplt.figure(1, [10, 5])\nloglog(h, err, '-*') ## makes a plot with a log scale on both the x and y axis\nloglog(h, d_err_q1, 'r-', label=r'$\\frac{h^2}{6}\\vert f^{\\prime\\prime\\prime}(x) \\vert $')\nplt.title(\"Q1 - Derivative Approximation\")\nxlabel('h', fontsize=20) ## puts a label on the x axis\nylabel('absolute error', fontsize=20) ## puts a label on the y axis\nylim(1e-15, 1) ## places limits on the yaxis for our plot\nlegend(fontsize=24); ## creates a figure legend\n\n\nplt.figure(2, [10,5])\nloglog(h, err1, '-*') ## makes a plot with a log scale on both the x and y axis\nloglog(h, d_err_example, 'r-', label=r'$\\frac{h}{2}\\vert f^{\\prime\\prime}(x) \\vert $')\nplt.title(\"Example 2 - Derivative Approximation\")\nxlabel('h', fontsize=20) ## puts a label on the x axis\nylabel('absolute error', fontsize=20) ## puts a label on the y axis\nylim(1e-15, 1) ## places limits on the yaxis for our plot\nlegend(fontsize=24); ## creates a figure legend", "meta": {"hexsha": "c751502bb4562a4e82b814291c05b80e01a68bfc", "size": 3947, "ext": "py", "lang": "Python", "max_stars_repo_path": "Finite-difference-error/numerical-derrivative-sin.py", "max_stars_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_stars_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Finite-difference-error/numerical-derrivative-sin.py", "max_issues_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_issues_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Finite-difference-error/numerical-derrivative-sin.py", "max_forks_repo_name": "Robertboy18/Numerical-Algorithms-Implementation", "max_forks_repo_head_hexsha": "e1ea13137d42ccc2502c590559edba750db4592d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.367816092, "max_line_length": 140, "alphanum_fraction": 0.6681023562, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446494481299, "lm_q2_score": 0.943347577479292, "lm_q1q2_score": 0.9184853213825678}} {"text": "# Use the following code for the exercises below:\n\nimport numpy as np\n\na = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7])\n\n#1 How many negative numbers are there?\n\nprint(f'There are {len(a[a < 0])} negative numbers in this array.')\n\n # There are 4 negative numbers in this array.\n\n#________________________________________________________________________\n\n#2 How many positive numbers are there?\n\nprint(f'There are {len(a[a > 0])} negative numbers in this array.')\n\n # There are 5 negative numbers in this array.\n#________________________________________________________________________\n\n#3 How many even positive numbers are there?\n\n#create array of positive numbers from a\npositives = a[a > 0]\n\n#use array filtering to filter only even numbers ###can use (& and) or (| or)\neven_and_positives = positives[positives % 2 == 0]\n\nprint(f'There are {len(even_and_positives)} numbers that are both even and positive.')\n\n # There are 3 numbers that are both even and positive.\n\n#ANOTHER WAY:\n\neven_positive_numbers = a[(a > 0) & (a % 2 == 0)]\neven_positive_numbers\n#________________________________________________________________________\n\n#4 If you were to add 3 to each data point, how many positive numbers would there be?\n\n# use vectorizing operation to add 3 to each element in the array\nplus_three = a + 3\n\n# use array filtering to filter only even numbers\npositive_and_plus_three = plus_three[plus_three > 0]\n\nprint(f'After we add 3 to each data point, there are {len(positive_and_plus_three)} positive numbers.')\n\n#________________________________________________________________________\n\n#5 If you squared each number, what would the new mean and standard deviation be?\n\n#create new array with squared elements\nsquared_elements = a ** 2\n\n#use array method .mean() to calculate the mean\nprint(f'The mean of the elements squared is: {squared_elements.mean()}')\n\n#use array method .std() to calculate standard deviation\nprint(f'The standard deviation of the elements squared is: {squared_elements.std()}')\n\n #The mean of the elements squared is: 74.0\n #The standard deviation of the elements squared is: 144.0243035046516\n\n\n#________________________________________________________________________\n\n#6 A common statistical operation on a dataset is centering. This means to adjust the data such that the mean of the data is 0. \n# This is done by subtracting the mean from each data point. Center the data set.\n\n# use vectorizing operation to subtract mean from each element of array a\ncentered_data_set = a - a.mean()\nprint(centered_data_set)\n\n #[ 1. 7. 9. 20. -5. -4. -3. -3. -3. -9. 0. -10.]\n\n#________________________________________________________________________\n \n #7 Calculate the z-score for each data point.\n\n #use vectoring operation to divide centered data set by standard deviation\n z_scores = centered_data_set / a.std()\n print(z_scores)\n\n # [ 0.12403473 0.86824314 1.11631261 2.48069469 -0.62017367 -0.49613894\n # -0.3721042 -0.3721042 -0.3721042 -1.11631261 0. -1.24034735]\n\n #________________________________________________________________________\n\n #8 MORE NUMPY PRACTICE: \n\n import numpy as np\n# Life w/o numpy to life with numpy\n\n## Setup 1\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n# Use python's built in functionality/operators to determine the following:\n\n# Exercise 1 - Make a variable called sum_of_a to hold the sum of all the numbers in above list\n\nsum_of_a = sum(a)\nprint(sum_of_a) #55\n\n# Exercise 2 - Make a variable named min_of_a to hold the minimum of all the numbers in the above list\n\nmin_of_a = min(a)\nprint(min_of_a) #1\n\n# Exercise 3 - Make a variable named max_of_a to hold the max number of all the numbers in the above list\n\nmax_of_a = max(a)\nprint(max_of_a) #10\n\n# Exercise 4 - Make a variable named mean_of_a to hold the average of all the numbers in the above list\n\nmean_of_a = sum(a) / len(a)\nprint(mean_of_a) #5.5\n\n# Exercise 5 - Make a variable named product_of_a to hold the product of multiplying all the numbers in the above list together\n\nproduct_of_a = 1\nfor n in a: \n product_of_a *= n\nprint(product_of_a) #3628800\n\n# Exercise 6 - Make a variable named squares_of_a. It should hold each number in a squared like [1, 4, 9, 16, 25...]\n\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nsquares_in_a = []\nfor i in a: \n squares_in_a.append(i ** 2)\nprint(squares_in_a) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n\n# Exercise 7 - Make a variable named odds_in_a. It should hold only the odd numbers\n\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nodds_in_a = []\nfor i in a: \n if i % 2 == 1:\n odds_in_a.append(i)\nprint(odds_in_a) # [1, 3, 5, 7, 9]\n\n# Exercise 8 - Make a variable named evens_in_a. It should hold only the evens.\n\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nevens_in_a = []\nfor i in a: \n if i % 2 == 0:\n evens_in_a.append(i)\nprint(evens_in_a) # [2, 4, 6, 8, 10]\n\n\n\n#####################################################\n\n## What about life in two dimensions? A list of lists is matrix, a table, a spreadsheet, a chessboard...\n## Setup 2: Consider what it would take to find the sum, min, max, average, sum, product, and list of squares for this list \n# of two lists.\n\nb = [\n [3, 4, 5],\n [6, 7, 8]\n]\n\n# Exercise 1 - refactor the following to use numpy. Use sum_of_b as the variable. **Hint, you'll first need to make sure that the \"b\" variable is a numpy array**\n# sum_of_b = 0\n# for row in b:\n# sum_of_b += sum(row)\n\nb = np.array(b)\n\nb.sum() #33\n\n# Exercise 2 - refactor the following to use numpy. \n# min_of_b = min(b[0]) if min(b[0]) <= min(b[1]) else min(b[1]) \n\nb.min() #3\n\n# Exercise 3 - refactor the following maximum calculation to find the answer with numpy.\n# max_of_b = max(b[0]) if max(b[0]) >= max(b[1]) else max(b[1])\n\nb.max() #8\n\n# Exercise 4 - refactor the following using numpy to find the mean of b\n# mean_of_b = (sum(b[0]) + sum(b[1])) / (len(b[0]) + len(b[1]))\n\nb.mean() #5.5\n\n# Exercise 5 - refactor the following to use numpy for calculating the product of all numbers multiplied together.\n# product_of_b = 1\n# for row in b:\n# for number in row:\n# product_of_b *= number\n\nb.prod() #20160\n \n# Exercise 6 - refactor the following to use numpy to find the list of squares \n# squares_of_b = []\n# for row in b:\n# for number in row:\n# squares_of_b.append(number**2)\n\nb ** 2\n# [[ 9 16 25]\n# [36 49 64]]\n\n\n# Exercise 7 - refactor using numpy to determine the odds_in_b\n# odds_in_b = []\n# for row in b:\n# for number in row:\n# if(number % 2 != 0):\n# odds_in_b.append(number)\n\n b[b % 2 != 0] # array([3, 5, 7])\n\n# Exercise 8 - refactor the following to use numpy to filter only the even numbers\n# evens_in_b = []\n# for row in b:\n# for number in row:\n# if(number % 2 == 0):\n# evens_in_b.append(number)\n\nb[b % 2 == 0] #array([4, 6, 8])\n\n# Exercise 9 - print out the shape of the array b.\nb.shape #(2, 3)\n\n# Exercise 10 - transpose the array b.\nb.T\n\n # array([[3, 6],\n # [4, 7],\n # [5, 8]])\n\n# Exercise 11 - reshape the array b to be a single list of 6 numbers. (1 x 6)\n\nb.reshape(6) #array([3, 4, 5, 6, 7, 8])\n\n# Exercise 12 - reshape the array b to be a list of 6 lists, each containing only 1 number (6 x 1)\n\nb.reshape(6,1)\n # array([[3],\n # [4],\n # [5],\n # [6],\n # [7],\n # [8]])\n\n\n\n##________________________________\n## Setup 3\nc = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n\n# HINT, you'll first need to make sure that the \"c\" variable is a numpy array prior to using numpy array methods.\n# Exercise 1 - Find the min, max, sum, and product of c.\nc = np.array(c)\n\nc.min(), c.max(), c.sum(), c.prod() #(1, 9, 45, 362880)\n\n# Exercise 2 - Determine the standard deviation of c.\nc.std() #2.581988897471611\n\n# Exercise 3 - Determine the variance of c.\nc.var() #6.666666666666667\n\n# Exercise 4 - Print out the shape of the array c\nc.shape() #(3, 3)\n\n# Exercise 5 - Transpose c and print out transposed result.\nc.T\n #array([[1, 4, 7],\n # [2, 5, 8],\n # [3, 6, 9]])\n\n# Exercise 6 - Get the dot product of the array c with c. \n\nnp.dot(c, c).sum() #729\n\n# Exercise 7 - Write the code necessary to sum up the result of c times c transposed. Answer should be 261\n\n(np.dot(c, c.T)).sum() #261\n\n# Exercise 8 - Write the code necessary to determine the product of c times c transposed. Answer should be 131681894400.\n \n\n## Setup 4\nd = [\n [90, 30, 45, 0, 120, 180],\n [45, -90, -30, 270, 90, 0],\n [60, 45, -45, 90, -45, 180]\n]\n\n# Exercise 1 - Find the sine of all the numbers in d\n\nnp.sin(d)\n\n # array([[ 0.89399666, -0.98803162, 0.85090352, 0. , 0.58061118,\n # -0.80115264],\n # [ 0.85090352, -0.89399666, 0.98803162, -0.17604595, 0.89399666,\n # 0. ],\n # [-0.30481062, 0.85090352, -0.85090352, 0.89399666, -0.85090352,\n # -0.80115264]])\n\n# Exercise 2 - Find the cosine of all the numbers in d\n\nnp.cos(d)\n\n # array([[-0.44807362, 0.15425145, 0.52532199, 1. , 0.81418097,\n # -0.59846007],\n # [ 0.52532199, -0.44807362, 0.15425145, 0.98438195, -0.44807362,\n # 1. ],\n # [-0.95241298, 0.52532199, 0.52532199, -0.44807362, 0.52532199,\n # -0.59846007]])\n\n\n# Exercise 3 - Find the tangent of all the numbers in d\n\nnp.tan(d)\n\n # array([[-1.99520041, -6.4053312 , 1.61977519, 0. , 0.71312301,\n # 1.33869021],\n # [ 1.61977519, 1.99520041, 6.4053312 , -0.17883906, -1.99520041,\n # 0. ],\n # [ 0.32004039, 1.61977519, -1.61977519, -1.99520041, -1.61977519,\n # 1.33869021]])\n\n# Exercise 4 - Find all the negative numbers in d\n\nd = np.array(d)\nd[d < 0] #array([-90, -30, -45, -45])\n\n# Exercise 5 - Find all the positive numbers in d\n\nd[d > 0] # array([ 90, 30, 45, 120, 180, 45, 270, 90, 60, 45, 90, 180])\n\n# Exercise 6 - Return an array of only the unique numbers in d.\n\nnp.unique(d) #array([-90, -45, -30, 0, 30, 45, 60, 90, 120, 180, 270])\n\n# Exercise 7 - Determine how many unique numbers there are in d.\n\nlen(np.unique(d)) #11\n\n# Exercise 8 - Print out the shape of d.\n\nd.shape # (3, 6)\n\n# Exercise 9 - Transpose and then print out the shape of d.\n\nd.T.shape #(6,3)\n\n# Exercise 10 - Reshape d into an array of 9 x 2\n\nd.reshape(9, 2)\n\n #array([[ 90, 30],\n # [ 45, 0],\n # [120, 180],\n # [ 45, -90],\n # [-30, 270],\n # [ 90, 0],\n # [ 60, 45],\n # [-45, 90],\n # [-45, 180]])\n", "meta": {"hexsha": "fd4062acca1086d5d4fec2be2ee8a19e0fa8e044", "size": 10622, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy_exercises.py", "max_stars_repo_name": "barbmarques/numpy-pandas-visualization-exercises", "max_stars_repo_head_hexsha": "2ecff3f668c940b35abe6e9812ce8c2bf260fdfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-28T02:21:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T21:57:08.000Z", "max_issues_repo_path": "numpy_exercises.py", "max_issues_repo_name": "barbmarques/numpy-pandas-visualization-exercises", "max_issues_repo_head_hexsha": "2ecff3f668c940b35abe6e9812ce8c2bf260fdfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy_exercises.py", "max_forks_repo_name": "barbmarques/numpy-pandas-visualization-exercises", "max_forks_repo_head_hexsha": "2ecff3f668c940b35abe6e9812ce8c2bf260fdfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.25, "max_line_length": 161, "alphanum_fraction": 0.6338730936, "include": true, "reason": "import numpy", "num_tokens": 3491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769099458929, "lm_q2_score": 0.9407897467685334, "lm_q1q2_score": 0.9178127540612249}} {"text": "import numpy as np \nimport matplotlib.pyplot as plt \nimport os\n\ndef f(x): # Function whose derivative we need to calculate\n\treturn np.sin(x)\n\ndef Df(x): # Exact derivative of f. This is used to compute error of the finite differences methods.\n\treturn np.cos(x)\n\n############################################\n# Functions to calculate forward (1st, 2nd and 3rd Order), backward(1st, 2nd and 3rd Order) and central(2nd and 4th Order) \n# difference based derivatives of a function f at x \n# with h=dx as the differnce between x_i and x_i+1.\n# The formulas for first, second and third order have been derived in the report.\n############################################\n\ndef forward_difference(f, x, dx):\n\n\t# 1st order\n\tderivative_forward_1 = (f(x+dx) - f(x))/dx\n\n\t# 2nd order\n\tderivative_forward_2 = (-f(x+2*dx) + 4*f(x+dx) - 3*f(x))/(2*dx)\n\t\n\t# 3rd order\n\tderivative_forward_3 = (2*f(x+3*dx) - 9*f(x+2*dx) + 18*f(x+dx) - 11*f(x))/(6*dx)\n\n\treturn derivative_forward_1, derivative_forward_2, derivative_forward_3\n\ndef backward_difference(f, x, dx):\n\n\t# 1st order\n\tderivative_backward_1 = (f(x) - f(x-dx))/dx\n\n\t# 2nd order\n\tderivative_backward_2 = (3*f(x) - 4*f(x-dx) + f(x-2*dx))/(2*dx)\n\t\n\t# 3rd order\n\tderivative_backward_3 = (4*f(x) - 7*f(x-dx) + 4*f(x-2*dx) - f(x-3*dx))/(2*dx)\n\n\treturn derivative_backward_1, derivative_backward_2, derivative_backward_3\n\ndef central_difference(f, x, dx):\n\n\t# 2nd order\n\tderivative_central_2 = (f(x+dx) - f(x-dx))/(2*dx)\n\n\t# 4th order\n\tderivative_central_4 = (-f(x+2*dx) + 8*f(x+dx) - 8*f(x-dx) + f(x-2*dx))/(12*dx)\n\n\treturn derivative_central_2, derivative_central_4\n\n\nsaved_graphs_dir = \"Graphs-Finite_Differences/\" # Folder to save the graphs\nif not os.path.exists(saved_graphs_dir):\n\tos.mkdir(saved_graphs_dir)\n\n# Define the dictionary to store errors of forward, backward and central difference methods for different orders\nforward_difference_error = {\n\t\"1st Order\" : [],\n\t\"2nd Order\": [],\n\t\"3rd Order\": []\n}\nbackward_difference_error = {\n\t\"1st Order\" : [],\n\t\"2nd Order\": [],\n\t\"3rd Order\": []\n}\ncentral_difference_error = {\n\t\"2nd Order\": [],\n\t\"4th Order\": []\n}\n\nx = 1 # Value whose derivative is to be evaluated\ndx_range = [] # Store the range of dx values. Used to plot the error values vs dx. \nexact_value = Df(x) # Exact value used to compute error. \n\nfor i in range(30):\n\tdx = 1/(2**i) # Half the value of dx after every iteration\n\t# print(dx)\n\tdx_range.append(dx)\n\tf1, f2, f3 = forward_difference(f, x, dx)\n\t# print((f1-exact_value)/exact_value)\n\tforward_difference_error[\"1st Order\"].append(abs(f1-exact_value)/exact_value)\n\tforward_difference_error[\"2nd Order\"].append(abs(f2-exact_value)/exact_value)\n\tforward_difference_error[\"3rd Order\"].append(abs(f3-exact_value)/exact_value)\n\n\tb1, b2, b3 = backward_difference(f, x, dx)\n\tbackward_difference_error[\"1st Order\"].append(abs(b1-exact_value)/exact_value)\n\tbackward_difference_error[\"2nd Order\"].append(abs(b2-exact_value)/exact_value)\n\tbackward_difference_error[\"3rd Order\"].append(abs(b3-exact_value)/exact_value)\n\n\tc2, c4 = central_difference(f, x, dx)\n\tcentral_difference_error[\"2nd Order\"].append(abs(c2-exact_value)/exact_value)\n\tcentral_difference_error[\"4th Order\"].append(abs(c4-exact_value)/exact_value)\n\n############################################\n# Plot Error vs dx graphs in Normal scaling\n############################################\n\nplt.plot(dx_range, forward_difference_error[\"1st Order\"])\nplt.plot(dx_range, forward_difference_error[\"2nd Order\"])\nplt.plot(dx_range, forward_difference_error[\"3rd Order\"])\nplt.legend([\"1st Order\", \"2nd Order\", \"3rd Order\"])\nplt.title(\"Forward Difference (normal scale)\")\nplt.xlabel(\"dx\")\nplt.ylabel(\"error\")\nplt.savefig(saved_graphs_dir + \"normal-scale-forward_difference.png\")\nplt.show()\n\nplt.plot(dx_range, backward_difference_error[\"1st Order\"])\nplt.plot(dx_range, backward_difference_error[\"2nd Order\"])\nplt.plot(dx_range, backward_difference_error[\"3rd Order\"])\nplt.legend([\"1st Order\", \"2nd Order\", \"3rd Order\"])\nplt.title(\"Backward Difference (normal scale)\")\nplt.xlabel(\"dx\")\nplt.ylabel(\"error\")\nplt.savefig(saved_graphs_dir + \"normal-scale-backward_difference.png\")\nplt.show()\n\nplt.plot(dx_range, central_difference_error[\"2nd Order\"])\nplt.plot(dx_range, central_difference_error[\"4th Order\"])\nplt.legend([\"2nd Order\", \"4th Order\"])\nplt.title(\"Central Difference (normal scale)\")\nplt.xlabel(\"dx\")\nplt.ylabel(\"error\")\nplt.savefig(saved_graphs_dir + \"normal-scale-central_difference.png\")\nplt.show()\n\nplt.plot(dx_range, forward_difference_error[\"2nd Order\"])\nplt.plot(dx_range, backward_difference_error[\"2nd Order\"])\nplt.plot(dx_range, central_difference_error[\"2nd Order\"])\nplt.legend([\"forward\", \"backward\", \"central\"])\nplt.title(\"Forward vs Backward Vs Central (2nd Order- Normal Scale)\")\nplt.xlabel(\"dx\")\nplt.ylabel(\"error\")\nplt.savefig(saved_graphs_dir + \"normal-scale-second_order.png\")\nplt.show()\n\nplt.plot(dx_range, forward_difference_error[\"1st Order\"])\nplt.plot(dx_range, forward_difference_error[\"2nd Order\"])\nplt.plot(dx_range, forward_difference_error[\"3rd Order\"])\nplt.plot(dx_range, backward_difference_error[\"1st Order\"])\nplt.plot(dx_range, backward_difference_error[\"2nd Order\"])\nplt.plot(dx_range, backward_difference_error[\"3rd Order\"])\nplt.plot(dx_range, central_difference_error[\"2nd Order\"])\nplt.plot(dx_range, central_difference_error[\"4th Order\"])\nplt.legend([\"Forward-1st Order\", \"Forward-2nd Order\", \"Forward-3rd Order\", \"Backward-1st Order\", \n\t\"Backward-2nd Order\", \"Backward-3rd Order\", \"Central-2nd Order\", \"Central-4th Order\"])\nplt.title(\"Forward vs Central vs Backward (Normal Scale)\")\nplt.xlabel(\"dx\")\nplt.ylabel(\"error\")\nplt.savefig(saved_graphs_dir + \"normal-scale-all.png\")\nplt.show()\n\n\n############################################\n# Plot Error vs dx graphs in log-log scaling\n############################################\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"1st Order\"]))\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"3rd Order\"]))\nplt.legend([\"1st Order\", \"2nd Order\", \"3rd Order\"])\nplt.title(\"Forward Difference (log-log scale)\")\nplt.xlabel(\"log(dx)\")\nplt.ylabel(\"log(error)\")\nplt.savefig(saved_graphs_dir + \"log-scale-forward_difference.png\")\nplt.show()\n\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"1st Order\"]))\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"3rd Order\"]))\nplt.legend([\"1st Order\", \"2nd Order\", \"3rd Order\"])\nplt.title(\"Backward Difference (log-log scale)\")\nplt.xlabel(\"log(dx)\")\nplt.ylabel(\"log(error)\")\nplt.savefig(saved_graphs_dir + \"log-scale-backward_difference.png\")\nplt.show()\n\nplt.plot(np.log2(dx_range), np.log2(central_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(central_difference_error[\"4th Order\"]))\nplt.legend([\"2nd Order\", \"4th Order\"])\nplt.title(\"Central Difference (log-log scale)\")\nplt.xlabel(\"log(dx)\")\nplt.ylabel(\"log(error)\")\nplt.savefig(saved_graphs_dir + \"log-scale-central_difference.png\")\nplt.show()\n\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(central_difference_error[\"2nd Order\"]))\nplt.legend([\"forward\", \"backward\", \"central\"])\nplt.title(\"Forward vs Backward Vs Central (2nd Order- log-log scale)\")\nplt.xlabel(\"log(dx)\")\nplt.ylabel(\"log(error)\")\nplt.savefig(saved_graphs_dir + \"log-scale-second_order.png\")\nplt.show()\n\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"1st Order\"]))\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(forward_difference_error[\"3rd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"1st Order\"]))\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(backward_difference_error[\"3rd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(central_difference_error[\"2nd Order\"]))\nplt.plot(np.log2(dx_range), np.log2(central_difference_error[\"4th Order\"]))\nplt.legend([\"Forward-1st Order\", \"Forward-2nd Order\", \"Forward-3rd Order\", \"Backward-1st Order\", \n\t\"Backward-2nd Order\", \"Backward-3rd Order\", \"Central-2nd Order\", \"Central-4th Order\"])\nplt.title(\"Forward vs Central vs Backward (Log Scale)\")\nplt.xlabel(\"log(dx)\")\nplt.ylabel(\"log(error)\")\nplt.savefig(saved_graphs_dir + \"log-scale-all.png\")\nplt.show()\n", "meta": {"hexsha": "7a16ad85f28f0fd9caa44220434559509d43df9f", "size": 8517, "ext": "py", "lang": "Python", "max_stars_repo_path": "HW1/finite_differences.py", "max_stars_repo_name": "krishnaw14/CFD-codes", "max_stars_repo_head_hexsha": "beaeb75da0a98c2b89cef82b68a866955b9133f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-27T08:25:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T17:41:30.000Z", "max_issues_repo_path": "HW1/finite_differences.py", "max_issues_repo_name": "krishnaw14/CFD-codes", "max_issues_repo_head_hexsha": "beaeb75da0a98c2b89cef82b68a866955b9133f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/finite_differences.py", "max_forks_repo_name": "krishnaw14/CFD-codes", "max_forks_repo_head_hexsha": "beaeb75da0a98c2b89cef82b68a866955b9133f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6139534884, "max_line_length": 123, "alphanum_fraction": 0.7200892333, "include": true, "reason": "import numpy", "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105307684549, "lm_q2_score": 0.9399133451974032, "lm_q1q2_score": 0.9176472969260306}} {"text": "#! Python3\n# What is the 10 001st prime number?\n# https://projecteuler.net/problem=7\n\n\n# 1st approach: Using python's sympy module. Pretty fast. \n#import sympy\n#goal = 10001 # trying to find goal'th prime number\n#i = j = 0\n#while i < goal:\n# j += 1\n# if sympy.isprime(j):\n# i += 1\n# print(i)\n#\n#print(i-1, 'th prime number is ', j)\n\n\n# 2nd aproach (takes about ?): Using sqrt from math module and own writen isprime function: Takes about 2 sec. Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked. And also algorith is further optimezed to just chech every 6th number TODO ?????? \n\ndef isprime(number):\n from math import sqrt\n # returns true if number is prime number\n assign = True\n for i in range (2,int(sqrt(number))+1):\n if number % i == 0:\n assign = False\n return assign \n\npri_list = [2,3]\ni = 1\nwhile len(pri_list) < 10001:\n if isprime(i*6-1): \n pri_list.append(i*6-1)\n if isprime(i*6+1): \n pri_list.append(i*6+1)\n i += 1\nprint(len(pri_list), 'th prime number is ', pri_list[-1])\n\n\n## 3rd aproach (takes about 2 seconds): Using just sqrt from math module and own writen isprime function: Takes about 2 sec. Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.\n#\n#def isprime(number):\n# from math import sqrt\n# # returns true if number is prime number\n# assign = True\n# for i in range (2,int(sqrt(number))+1):\n# if number % i == 0:\n# assign = False\n# return assign \n#goal = 10001 # trying to find goal'th prime number\n#i = j = 0\n#while i <= goal:\n# j += 1\n# if isprime(j):\n# i += 1\n#\n#print(i, 'th prime number is ', j)\n\n\n## 4th approach: Naive brute force, using self written isprime function. It takes about 2 minutes to compute. That's why kept it at 100th for now.\n#def isprime(number):\n# # returns true if number is prime number\n# assign = True\n# for i in range (2,number):\n# if number % i == 0:\n# assign = False\n# return assign \n#\n#goal = 100 # trying to find goal'th prime number\n#i = j = 0\n#while i <= goal:\n# j += 1\n# if isprime(j):\n# i += 1\n# print(i)\n#\n#print(i-1, 'th prime number is ', j)\n", "meta": {"hexsha": "458e3ff17936c02fc00f69594d862a952e7dc6d5", "size": 2374, "ext": "py", "lang": "Python", "max_stars_repo_path": "files/007 - 10001st prime.py", "max_stars_repo_name": "farukara/Project-Euler-problems", "max_stars_repo_head_hexsha": "806fdbd797edd9929728b43cc428a55df50e1c01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "files/007 - 10001st prime.py", "max_issues_repo_name": "farukara/Project-Euler-problems", "max_issues_repo_head_hexsha": "806fdbd797edd9929728b43cc428a55df50e1c01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/007 - 10001st prime.py", "max_forks_repo_name": "farukara/Project-Euler-problems", "max_forks_repo_head_hexsha": "806fdbd797edd9929728b43cc428a55df50e1c01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0506329114, "max_line_length": 339, "alphanum_fraction": 0.6284751474, "include": true, "reason": "import sympy", "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517411671126, "lm_q2_score": 0.9381240151413301, "lm_q1q2_score": 0.9175338264396606}} {"text": "import numpy as np\nfrom numpy.random import uniform\n\nfrom numerical.linear_equations import iterative\nfrom numerical.linear_equations import iterative_sor, iterative_gauss_seidel\n\n\ndef demo_0():\n # Matt and Jane are selling fruit. Buyers can purchase small boxes of\n # apples and large boxes of apples. Matt sold 3 small boxes and 14 large\n # boxes for a total of 203€. Jane sold 11 small boxes and 11 large boxes\n # for a total of 220€. How much do the boxes cost? (the correct solution\n # is 7€ and 13€)\n\n # 3 x_0 + 14 x_1 = 203\n # 11 x_0 + 11 x_1 = 220\n A = np.array([\n [3, 14],\n [11, 11]])\n b = np.array([203, 220])\n\n result = iterative(A, b, x0=np.zeros(b.shape), acc=1e-7, omega=1)\n\n # let's take a look if the returned solution is correct\n print(\"Small box price: {:.2f}€\".format(result['x'][0]))\n print(\"Large box price: {:.2f}€\".format(result['x'][1]))\n\n # how many iterations were needed with different iterative methods?\n print(\"Number of iterations needed to find the solution:\")\n print(\"Jacobi: {:d}\".format(result['j_num_iter']))\n print(\"Gauss-Seidel: {:d}\".format(result['gs_num_iter']))\n print(\"SOR: {:d}\".format(result['sor_num_iter']))\n\n\ndef demo_1():\n A = np.array([\n [2, -1, 0, 0],\n [-1, 2, -1, 0],\n [0, -1, 2, -1],\n [0, 0, -1, 2]])\n b = np.array([1, 0, 0, 1])\n\n # let's compare number of iterations for the Gauss-Seidel\n # method and the SOR method\n _, gs_num_iter = iterative_gauss_seidel(\n A, b,\n x0=np.zeros(b.shape),\n acc=1e-7,\n )\n _, sor_num_iter = iterative_sor(\n A, b,\n x0=np.zeros(b.shape),\n acc=1e-7,\n omega=1\n )\n print(\"Number of iterations needed to find the solution:\")\n print(\"Gauss-Seidel: {:d}\".format(gs_num_iter))\n print(\"SOR with omega = 1: {:d}\".format(sor_num_iter))\n\n # can we do better? -> random search\n fastest_convergence = (sor_num_iter, 1)\n\n for _ in range(100):\n omega = uniform(0, 2)\n _, sor_num_iter = iterative_sor(\n A, b,\n x0=np.zeros(b.shape),\n acc=1e-7,\n omega=omega\n )\n\n if sor_num_iter < fastest_convergence[0]:\n fastest_convergence = (sor_num_iter, omega)\n\n str_ = \"SOR with omega = {:f}: {:d}\"\n print(str_.format(fastest_convergence[1], fastest_convergence[0]))\n\n\nif __name__ == '__main__':\n demo_0()\n print()\n demo_1()\n", "meta": {"hexsha": "91a349afd166cb61d2f7e43e9bf1dc0aa90d0209", "size": 2465, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/demo_linear_equations.py", "max_stars_repo_name": "inejc/numerical", "max_stars_repo_head_hexsha": "38bd2a394c05e4d726c2ea0c9bf4f1dbd2fb59b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/demo_linear_equations.py", "max_issues_repo_name": "inejc/numerical", "max_issues_repo_head_hexsha": "38bd2a394c05e4d726c2ea0c9bf4f1dbd2fb59b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/demo_linear_equations.py", "max_forks_repo_name": "inejc/numerical", "max_forks_repo_head_hexsha": "38bd2a394c05e4d726c2ea0c9bf4f1dbd2fb59b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6987951807, "max_line_length": 76, "alphanum_fraction": 0.5975659229, "include": true, "reason": "import numpy,from numpy", "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290897113961, "lm_q2_score": 0.944176857294597, "lm_q1q2_score": 0.9169176119510687}} {"text": "\n# coding: utf-8\n\n# ## Linear Regression using Gradient Descent\n# \n# In this notebook, I've built a simple linear regression model using gradient descent to fit a line ($y = mx + c$) through input data consisting of ($x, y$) values. The purpose is to better understand gradient descent by calculating the gradients by hand and implementing it without using out-of-the-box libraries/ methods.\n# \n# ### Problem Statement\n# \n# **Given a set of $x$ and $y$ values, the problem statement here is to find a line \"$y = mx + b$\" that best fits the data**. This involes finding the values of $m$ and $b$ that minimizes an _Error/ Loss_ function for the given dataset. We will use _Mean Squared Error (denoted as E)_ as the error function to be minimized, and it is given by - \n# \n# $E = \\dfrac{1}{N} \\sum_{i=1}^N (y_i - (mx_i + b))^2$\n# \n# To find the optimial value of $m$ and $b$ that minimizes the error function using Gradient Descent, the values are randomly initialized first and then updated $number of steps$ times or until the error function value converges. Below equations are used to update the values of $m$ and $b$ at each step -\n# \n# $\n# m = m - learning\\_rate \\times \\dfrac{\\partial E}{\\partial m}\n# $\n# \n# $\n# b = b - learning\\_rate \\times \\dfrac{\\partial E}{\\partial b}\n# $\n# \n# ### Calculating Gradients for Mean Squared Error \n# \n# The Gradient Descent update formulae given above needs the partial derivatives of error function $E$ with respect to both $m$ and $b$ ($\\dfrac{\\partial E}{\\partial m}$ and $\\dfrac{\\partial E}{\\partial b}$ respectively). These partial derivatives are calculated as follows -\n# \n# $\n# \\begin{align}\n# E &= \\dfrac{1}{N} \\sum_{i=1}^N (y_i - (mx_i + b))^2 \\\\\n# &= \\dfrac{1}{N} \\sum_{i=1}^N y_i^2 - 2y_i(mx_i + b) + (mx_i + b)^2 \\\\ \n# &= \\dfrac{1}{N} \\sum_{i=1}^N y_i^2 - 2x_iy_im - 2y_ib + x_i^2m^2 + 2x_imb + b^2 \\\\\n# \\end{align}\n# $\n# \n# $\n# \\begin{align}\n# \\dfrac{\\partial E}{\\partial m} &= \\dfrac{1}{N} \\sum_{i=1}^N 0 - 2x_iy_i - 0 + 2x_i^2m + 2x_ib + 0 \\\\\n# &= \\dfrac{-2}{N} \\sum_{i=1}^N x_i(y_i - (mx_i + b))\n# \\end{align}\n# $\n# \n# $\n# \\begin{align}\n# \\dfrac{\\partial E}{\\partial b} &= \\dfrac{1}{N} \\sum_{i=1}^N 0 - 0 - 2y_i + 0 + 2x_im + 2b \\\\\n# &= \\dfrac{-2}{N} \\sum_{i=1}^N (y_i - (mx_i + b))\n# \\end{align}\n# $\n# \n# \n# \n# \n# \n\n# ## Implementation\n\n# In[1]:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nget_ipython().magic('matplotlib inline')\n\ndef plot_fit(points, m, b, step, error):\n '''\n Plots a scatterplot of points, with a line defined by m and b.\n Also shows the current step number in Gradient Descent and \n current error value.\n '''\n \n x_values = [p[0] for p in points]\n y_values = [p[1] for p in points]\n \n plt.scatter(x_values, y_values, color='skyblue') \n fit_xvalues = list(range(int(min(x_values)), int(max(x_values))))\n fit_yvalues = [m * fit_x + b for fit_x in fit_xvalues]\n plt.plot(fit_xvalues, fit_yvalues, color='blue')\n plt.title('Step: ' + str(step) + ', Error:' + str(round(error, 2)))\n plt.show()\n\ndef mean_squared_error(points, m, b):\n '''\n Calculates Mean Squared Error for the line defined by m & b\n with the given points.\n '''\n n = len(points)\n error = 0\n \n for i in range(n):\n x_i = points[i, 0]\n y_i = points[i, 1]\n \n error += (y_i - (m * x_i + b)) **2\n \n error = float(error) / n\n \n return error\n\ndef gradient_step(points, current_m, current_b, learning_rate):\n '''\n Calculates gradients and new values for m and b based on\n current values of m and b and given learning rate.\n '''\n gradient_m = 0\n gradient_b = 0\n \n n = len(points)\n \n for i in range(n):\n x_i = float(points[i, 0])\n y_i = float(points[i, 1])\n \n gradient_m += (-2 / n) * (x_i * (y_i - (current_m * x_i + current_b)))\n gradient_b += (-2 / n) * (y_i - (current_m * x_i + current_b))\n \n new_m = current_m - learning_rate * gradient_m\n new_b = current_b - learning_rate * gradient_b\n new_error = mean_squared_error(points, new_m, new_b)\n \n return [new_m, new_b, new_error]\n \ndef gradient_descent(points, initial_m, initial_b, learning_rate, num_steps):\n '''\n Runs Gradient Descent for the given points, starting with the initial\n m and b values, and the given learning rate for the given number of steps.\n '''\n m = initial_m\n b = initial_b\n \n error_vec = list()\n \n # Update m and b for each gradient descent step\n for step in range(num_steps):\n \n [m, b, error] = gradient_step(points, m, b, learning_rate)\n\n # Plot the current fit once every 100 steps to track progress\n if not step % 100: \n plot_fit(points, m, b, step, error)\n \n error_vec.append(error)\n \n # Plot the error function value for each step\n plt.plot(error_vec, color='red')\n plt.xlabel('Number of Steps')\n plt.ylabel('Mean Squared Error')\n plt.show()\n \n return [m, b]\n\ndef run():\n points = np.genfromtxt('data.csv', delimiter=',')\n \n initial_m = 0\n initial_b = 0\n \n learning_rate = 0.0001\n num_steps = 1000\n \n m, b = gradient_descent(points, initial_m, initial_b, learning_rate, num_steps)\n \nif __name__ == '__main__':\n run()\n\n", "meta": {"hexsha": "5d38087d28b64bab88a6baabb7e8e4d754f556c8", "size": 5362, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-regression-gradient-descent/gradient_descent.py", "max_stars_repo_name": "cijogeorge/workspace-machine-learning", "max_stars_repo_head_hexsha": "a8d16d4b1fa6a9549eff28307e3e2f73bc661038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-regression-gradient-descent/gradient_descent.py", "max_issues_repo_name": "cijogeorge/workspace-machine-learning", "max_issues_repo_head_hexsha": "a8d16d4b1fa6a9549eff28307e3e2f73bc661038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-regression-gradient-descent/gradient_descent.py", "max_forks_repo_name": "cijogeorge/workspace-machine-learning", "max_forks_repo_head_hexsha": "a8d16d4b1fa6a9549eff28307e3e2f73bc661038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.496969697, "max_line_length": 345, "alphanum_fraction": 0.6122715405, "include": true, "reason": "import numpy", "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307676766119, "lm_q2_score": 0.9425067272555726, "lm_q1q2_score": 0.9168995430164097}} {"text": "import numpy as np\r\n\r\n# Mathematical functions\r\na = np.array([0,30,45,60,90]) \r\n# Note: all the functions take radian as angle\r\n\r\n# sin\r\nprint (\"print sin: \", np.sin(a*np.pi/180))\r\n\r\n# cos\r\nprint (\"print cos: \", np.cos(a*np.pi/180))\r\n\r\n# tan\r\nprint (\"print tan: \", np.tan(a*np.pi/180))\r\n\r\n# arcsin\r\nsin = np.sin(a*np.pi/180)\r\ninv = np.arcsin(sin)\r\nprint(\"inv sin: \", np.degrees(inv))\r\n\r\n# arccos\r\ncos = np.cos(a*np.pi/180)\r\ninv = np.arccos(cos)\r\nprint(\"inv sin: \", np.degrees(inv))\r\n\r\n# arctan\r\ntan = np.tan(a*np.pi/180)\r\ninv = np.arctan(tan)\r\nprint(\"inv sin: \", np.degrees(inv))\r\n\r\n\r\n# Rounding ops\r\n# Syantax: \r\n#numpy.around(a,decimals)\r\n# decimals -> The number of decimals to round to. Default is 0. If negative, the integer is rounded to position to the left of the decimal point\r\n\r\na = np.array([1.0,5.55, 123, 0.567, 25.532]) \r\nprint(\"Round: \", np.round(a))\r\nprint(\"Round deci = 1 \", np.round(a, decimals = 1))\r\nprint(\"Round deci = -1 \", np.round(a, decimals = -1))\r\n\r\n# floor: This function returns the largest integer not greater than the input parameter. \r\na = np.array([-1.7, 1.5, -0.2, 0.6, 10]) \r\nprint(\"Floor ops: \", np.floor(a))\r\n\r\n# ceil: The ceil() function returns the ceiling of an input value, i.e. the ceil of the scalar x is the smallest integer i, such that i >= x\r\nprint(\"Ceil ops: \", np.ceil(a))\r\n\r\n# add, subtract, multiple, divide \r\n# Note: all the ops follow broadcasting and element-wise rules\r\na = np.arange(9, dtype = np.float_).reshape(3,3) \r\nb = np.array([10,10,10]) \r\n\r\nprint(\"a: \\n\", a)\r\nprint(\"b: \\n\", b)\r\nprint(\"add array: \", np.add(a,b))\r\nprint(\"subtract array: \", np.subtract(a,b))\r\nprint(\"add multiply: \", np.multiply(a,b))\r\nprint(\"add divide: \", np.divide(a,b))\r\n\r\n# power\r\na = np.array([10,100,1000])\r\nprint(\"power with scalar: \", np.power(a, 2))\r\nb = np.array([1,2, 3])\r\nprint(\"power with array elementwise: \", np.power(a, b))\r\n\r\n# mod or remainder\r\na = np.array([10,20,30]) \r\nb = np.array([3,5,7]) \r\n\r\nprint(\"mod with scalar: \", np.mod(1, 4))\r\nprint(\"mod with array elementwise: \", np.mod(a,b))\r\nprint(\"remainder with elementwise: \", np.remainder(a,b))\r\n\r\n", "meta": {"hexsha": "43881a91589cbadabfc2bdfe0506f2de21be8e73", "size": 2102, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpu-tuto/numpy_rev_math_arthi_ops.py", "max_stars_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_stars_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpu-tuto/numpy_rev_math_arthi_ops.py", "max_issues_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_issues_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpu-tuto/numpy_rev_math_arthi_ops.py", "max_forks_repo_name": "sourabhyadav/100-days-0f-DL-DevOps", "max_forks_repo_head_hexsha": "51bd1636323d117c7e2e11b62941efac5d4f2d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0266666667, "max_line_length": 145, "alphanum_fraction": 0.6289248335, "include": true, "reason": "import numpy", "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446532718788, "lm_q2_score": 0.9416541581602784, "lm_q1q2_score": 0.9168365363239872}} {"text": "\"\"\"\n\nhttp://cs-people.bu.edu/sbargal/Fall%202016/lecture_notes/Nov_3_3d_geometry_representation\nhttps://en.wikipedia.org/wiki/Quadratic_form\nhttps://en.wikipedia.org/wiki/Conic_section\nhttps://en.wikipedia.org/wiki/Matrix_representation_of_conic_sections\n\n\"\"\"\n\nimport numpy as np\nfrom sympy import *\n\ndef print_implicit(title, Q, p, eig=True):\n M = Matrix(Q)\n v = expand(np.dot(p.T, np.dot(Q, p)))\n n = 2 * np.dot(Q, p)\n print(title)\n print(\"Matrix\")\n pprint(M)\n print(\"Implicit\")\n print(v)\n print(\"Normal\")\n print(n[:len(n)-1])\n print(\"Determinant\")\n print(M.det())\n if eig:\n print(\"Eigenvalues and Eigenvectors\")\n pprint(M.eigenvals())\n pprint(M.eigenvects())\n print()\n\n\n\"\"\"\n\nConic sections can be viewed as a 2D quadric surface and can be represented by the 3x3 symmetric matrix\nM = [A B/2 D/2\n B/2 C E/2\n D/2 E/2 F]\n\nwhere A-F are constants\n\nTo test if a point lies on the conic section we can do\np = [x y 1] (homogeneous point)\ntranspose(p) * M * p = 0\n\nIf we symbolically multiply the equation above out, we get \nA*x**2 + B*x*y + C*y**2 + D*x + E*y + F = 0\n\nThe determinant of the matrix M gives us what \"shape\" of the solution set is\ndet(M) < 0 gives ellipse (If A=C, B=0), gives us a circle\ndet(M) = 0 gives parabola\ndet(M) > 0 gives hyperbola (if A+C = 0), gives us a rectangular hyperbola\n\nCircle\nM = [1 0 0\n 0 1 0\n 0 0 -r^2]\n\nx^2 + y^2 - r^2\n\nEllipse\nM = [1/a^2 0 0\n 0 1/b^2 0\n 0 0 -1]\n\nx^2/a^2 + y^2/b^2 - 1\n\nParabola\nM = [4a/x 0 0\n 0 -1 0\n 0 0 0]\n\ny^2 = 4ax\n\nHyperbola\nM = [1/a^2 0 0\n 0 -1/b^2 0\n 0 0 -1]\n\nx^2/a^2 - y^2/b^2 = 1\n\n\"\"\"\ndef test_implicit_matrix_form_2d():\n A = Symbol('A')\n B = Symbol('B')\n C = Symbol('C')\n D = Symbol('D')\n E = Symbol('E')\n F = Symbol('F')\n\n x = Symbol('x')\n y = Symbol('y')\n r = Symbol('r')\n a = Symbol('a')\n b = Symbol('b')\n p = np.array([x, y, 1])\n\n print(\"Conic Sections Implicit Matrix Form\")\n\n Q = np.array([[A, B/2, D/2], [B/2, C, E/2], [D/2, E/2, F]])\n print_implicit(\"General\", Q, p, eig=False)\n\n Q = np.array([[1, 0, 0], [0, 1, 0], [0, 0, -(r*r)]])\n print_implicit(\"Circle\", Q, p)\n\n Q = np.array([[1/(a*a), 0, 0], [0, 1/(b*b), 0], [0, 0, -1]])\n print_implicit(\"Ellipse\", Q, p)\n\n Q = np.array([[1/(a*a), 0, 0], [0, -1/(b*b), 0], [0, 0, -1]])\n print_implicit(\"Hyperbola\", Q, p)\n\n Q = np.array([[4*a/x, 0, 0], [0, -1, 0], [0, 0, 0]])\n print_implicit(\"Parabola\", Q, p)\n\n\"\"\"\n\nImplicit equations that describe quadric surfaces can be represented as a 4x4 symmetric matrix\nM = [A B C D\n B E F G\n C F H I\n D G I J]\n\nwhere A-J are constants\n\nTo test whether a point (represented in homogenous form)\np = [x y z 1] lies on the quadric surface we have\n\ntranpose(p) * M * p = 0\n\nIf we symbolically do the matrix multiplication above, we get this equation:\nA*x**2 + 2*B*x*y + 2*C*x*z + 2*D*x + E*y**2 + 2*F*y*z + 2*G*y + H*z**2 + J + 2*I*z = 0\n\nIn a sense, M is a matrix of a quadratic form\ntranspose(x)*A*x + transpose(b)*x = c\nand transpose(b)*x and c is 0 in this case\nThe eigenvalues of A determine the \"shape\" solution set, such as a ellipsoid or hyperboloid\n\nIf all eigenvalues of A are positive, then it is a ellipsoid\nIf all eigenvalues of A are negative, then it is a imginary ellipsoid\nIf some eigenvalues are positive and some negative, it is a hyperboloid\nIf one or more eigenvalues is zero, then the shape depends on the b vector, then it can be elliptic/hyperbolic paraboloid\n\nThe normal can be calculated by taking the gradient of equation\ngradient(transpose(p) * M * p) = 2*Q*p\nThis gives us the normal vector for every point that is determined to be on the surface by the implicit form\n\nDepending what we set the constants A-J as, we can get a sphere, hyperbolas, ellipsoid, cones\n\nSphere\nM = [1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 -r^2]\n\nN = [2x 2y 2z]\n\nx^2 + y^2 + z^2 - r^2\n\nEllipsoid\nM = [1/rx^2 0 0 0\n 0 1/ry^2 0 0\n 0 0 1/rz^2 0\n 0 0 0 -1]\n\nN = [2*x/rx^2 2*y/ry^2 2*z/rz^2]\n\nx^2/rx^2 + y^2/ry^2 + z^2/rz^2 - 1\n\nCylinder\nM = [1/rx^2 0 0 0\n 0 1/ry^2 0 0\n 0 0 0 0\n 0 0 0 -1]\n\nN = [2*x/rx^2 2*y/ry^2 0]\n\nx^2/rx^2 + y^2/ry^2 - 1\n\nCone\nM = [1/rx^2 0 0 0\n 0 1/ry^2 0 0\n 0 0 -1/s^2 0\n 0 0 0 0]\n\nN = [2*x/rx^2 2*y/ry^2 -2*z/s^2]\n\nx^2/rx^2 + y^2/ry^2 - z^2/s^2\n\nPlane (Not a quadric surface but it can be represented in this form)\nM = [0 0 0 a/2\n 0 0 0 b/2\n 0 0 0 c/2\n a/2 b/2 c/2 -d]\n\nN = [a b c]\n\nax + by + cz - d\n\n\"\"\"\ndef test_implicit_matrix_form_3d():\n A = Symbol('A')\n B = Symbol('B')\n C = Symbol('C')\n D = Symbol('D')\n E = Symbol('E')\n F = Symbol('F')\n G = Symbol('G')\n H = Symbol('H')\n J = Symbol('J')\n \n a = Symbol('a')\n b = Symbol('b')\n c = Symbol('c')\n d = Symbol('d')\n r = Symbol('r')\n s = Symbol('s')\n rx = Symbol('rx')\n ry = Symbol('ry')\n rz = Symbol('rz')\n\n x = Symbol('x')\n y = Symbol('y')\n z = Symbol('z')\n s = Symbol('s')\n p = np.array([x, y, z, 1])\n\n print(\"Quadric Surfaces Implicit Matrix Form\")\n print()\n \n Q = np.array([[A, B, C, D], [B, E, F, G], [C, F, H, I], [D, G, I, J]])\n print_implicit(\"General\", Q, p, eig=False)\n\n Q = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -(r*r)]])\n print_implicit(\"Sphere\", Q, p)\n\n Q = np.array([[1/(rx*rx), 0, 0, 0], [0, 1/(ry*ry), 0, 0], [0, 0, 1/(rz*rz), 0], [0, 0, 0, -1]])\n print_implicit(\"Ellipsoid\", Q, p)\n\n Q = np.array([[1/(rx*rx), 0, 0, 0], [0, 1/(ry*ry), 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]])\n print_implicit(\"Cylinder\", Q, p)\n\n Q = np.array([[1/(rx*rx), 0, 0, 0], [0, 1/(ry*ry), 0, 0], [0, 0, -1/(s*s), 0], [0, 0, 0, 0]])\n print_implicit(\"Cone\", Q, p)\n\n Q = np.array([[0, 0, 0, a/2], [0, 0, 0, b/2], [0, 0, 0, c/2], [a/2, b/2, c/2, -d]])\n print_implicit(\"Plane\", Q, p)\n\ninit_printing()\ntest_implicit_matrix_form_2d()\nprint(\"\")\ntest_implicit_matrix_form_3d()\n", "meta": {"hexsha": "192b2e7d13502a1d3ae1f5eab7e0515e91ac19d2", "size": 5954, "ext": "py", "lang": "Python", "max_stars_repo_path": "math/quadric-surface.py", "max_stars_repo_name": "qeedquan/misc_utilities", "max_stars_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:02:53.000Z", "max_issues_repo_path": "math/quadric-surface.py", "max_issues_repo_name": "qeedquan/misc_utilities", "max_issues_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/quadric-surface.py", "max_forks_repo_name": "qeedquan/misc_utilities", "max_forks_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:10:59.000Z", "avg_line_length": 23.626984127, "max_line_length": 121, "alphanum_fraction": 0.5619751428, "include": true, "reason": "import numpy,from sympy", "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9863631619124993, "lm_q2_score": 0.9294404067444035, "lm_q1q2_score": 0.9167657784056493}} {"text": "import numpy as np\nfrom scipy.interpolate import CubicSpline\n\n# calculate 5 natural cubic spline polynomials for 6 points\n# (x,y) = (0,12) (1,14) (2,22) (3,39) (4,58) (5,77)\nx = np.array([0, 1, 2, 3, 4, 5])\ny = np.array([12,14,22,39,58,77])\n\n# calculate natural cubic spline polynomials\ncs = CubicSpline(x,y,bc_type='natural')\n\n# show values of interpolation function at x=1.25\nprint('S(1.25) = ', cs(1.25))\n\n## Aditional - find polynomial coefficients for different x regions\n\n# if you want to print polynomial coefficients in form\n# S0(0<=x<=1) = a0 + b0(x-x0) + c0(x-x0)^2 + d0(x-x0)^3\n# S1(1< x<=2) = a1 + b1(x-x1) + c1(x-x1)^2 + d1(x-x1)^3\n# ...\n# S4(4< x<=5) = a4 + b4(x-x4) + c5(x-x4)^2 + d5(x-x4)^3\n# x0 = 0; x1 = 1; x4 = 4; (start of x region interval)\n\n# show values of a0, b0, c0, d0, a1, b1, c1, d1 ...\n\ncs.c\ncoeffsAll = cs.c\nprint(cs.c)\nprint(\"a0 is \" + str(coeffsAll[3][0]) )\n\n# Polynomial coefficients for 0 <= x <= 1\na0 = cs.c.item(3,0)\nprint(\"a0 is \" + str(a0) )\n\nb0 = cs.c.item(2,0)\nc0 = cs.c.item(1,0)\nd0 = cs.c.item(0,0)\n\n# Polynomial coefficients for 1 < x <= 2\na1 = cs.c.item(3,1)\nb1 = cs.c.item(2,1)\nc1 = cs.c.item(1,1)\nd1 = cs.c.item(0,1)\n\n# Polynomial coefficients for 2 < x <= 3\na2 = cs.c.item(3,2)\nb2 = cs.c.item(2,2)\nc2 = cs.c.item(1,2)\nd2 = cs.c.item(0,2)\n\n# Polynomial coefficients for 3 < x <= 4\na3 = cs.c.item(3,3)\nb3 = cs.c.item(2,3)\nc3 = cs.c.item(1,3)\nd3 = cs.c.item(0,3)\n\n# Polynomial coefficients for 4 < x <= 5\na4 = cs.c.item(3,4)\nb4 = cs.c.item(2,4)\nc4 = cs.c.item(1,4)\nd4 = cs.c.item(0,4)\n\n\n\n# Print polynomial equations for different x regions\nprint('S0(0<=x<=1) = ', a0, ' + ', b0, '(x-0) + ', c0, '(x-0)^2 + ', d0, '(x-0)^3')\nprint('S1(1< x<=2) = ', a1, ' + ', b1, '(x-1) + ', c1, '(x-1)^2 + ', d1, '(x-1)^3')\n\nprint('...')\n#print('S5(4< x<=5) = ', a4, ' + ', b4, '(x-4) + ', c4, '(x-4)^2 + ', d4, '(x-4)^3')\n#print(str(a0)+\", \"+str(b0)+\", \"+str(c0)+\", \"+str(d0)+\", \")\n#print(str(a1)+\", \"+str(b1)+\", \"+str(c1)+\", \"+str(d1)+\", \")\n#print(str(a2)+\", \"+str(b2)+\", \"+str(c2)+\", \"+str(d2)+\", \")\n#print(str(a3)+\", \"+str(b3)+\", \"+str(c3)+\", \"+str(d3)+\", \")\n#print(str(a4)+\", \"+str(b4)+\", \"+str(c4)+\", \"+str(d4)+\", \")\n\n# So we can calculate S(1.25) by using equation S1(1< x<=2)\n#print('S(1.25) = ', a1 + b1*0.25 + c1*(0.25**2) + d1*(0.25**3))\n\nx = np.array([0, 1, 2, 3, 4, 5])\ny[0:3] = y[3:6]\ny[3:6] = [56,745,346] # New values. \n\n\n# calculate natural cubic spline polynomials from 0 to 5 \ncs = CubicSpline(x,y,bc_type='natural')\n\n# send c4,c3,c2s to stm and interpolate according to those vals. \n# Split those vals in stm according to the timestamps. \n\n# Cubic spline interpolation calculus example\n# https://www.youtube.com/watch?v=gT7F3TWihvk\n", "meta": {"hexsha": "73f42e9b33e6c23ae1ff8cac4b659ec224ce590d", "size": 2690, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/playground/splinetest.py", "max_stars_repo_name": "manavjain99/oscar_buggy", "max_stars_repo_head_hexsha": "b5dab0848f8667c9515bcfb078730cd0c4060000", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/playground/splinetest.py", "max_issues_repo_name": "manavjain99/oscar_buggy", "max_issues_repo_head_hexsha": "b5dab0848f8667c9515bcfb078730cd0c4060000", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/playground/splinetest.py", "max_forks_repo_name": "manavjain99/oscar_buggy", "max_forks_repo_head_hexsha": "b5dab0848f8667c9515bcfb078730cd0c4060000", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9247311828, "max_line_length": 85, "alphanum_fraction": 0.5676579926, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971992482639258, "lm_q2_score": 0.9425067276593031, "lm_q1q2_score": 0.916109454121769}} {"text": "import numpy as np\r\nimport matplotlib.pylab as plt\r\n\r\n########### Differentiation ##################\r\n\r\nprint('Differentiation')\r\nprint('\\n')\r\n\r\ndef fun(x):\r\n\treturn np.sin(x)\r\n\r\nx = np.linspace(0,np.pi,1000)\r\ny = fun(x)\r\n\r\nplt.figure()\r\nplt.plot(x,y)\r\nplt.grid(1)\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.savefig('sin(x).png')\r\n\r\ndef fun_prime(x):\r\n\treturn np.cos(x)\r\n\r\ny_prime = fun_prime(x)\r\n\r\nplt.figure()\r\nplt.plot(x,y_prime)\r\nplt.grid(1)\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.savefig('sin_prime(x).png')\r\n\r\ndef forward_difference(x,y):\r\n\th = (max(x)-min(x))/float(len(x)-1)\r\n\tprime = (y[1:]-y[0:-1])/float(h)\r\n\treturn prime\r\n\r\ny_prime_forward = forward_difference(x,y)\r\n\r\nplt.figure()\r\nplt.plot(x[:-1],y_prime_forward)\r\nplt.grid(1)\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.savefig('sin_prime_forward(x).png')\r\n\r\ndef backward_difference(x,y):\r\n\th = (max(x)-min(x))/float(len(x)-1)\r\n\tprime = (y[1:]-y[0:-1])/float(h)\r\n\treturn prime\r\n\r\ny_prime_backward = backward_difference(x,y)\r\n\r\nplt.figure()\r\nplt.plot(x[1:],y_prime_backward)\r\nplt.grid(1)\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.savefig('sin_prime_backward(x).png')\r\n\r\ndef central_difference(x,y):\r\n\th = (max(x)-min(x))/float(len(x)-1)\r\n\tprime = (y[2:]-y[0:-2])/float(2*h)\r\n\treturn prime\r\n\r\ny_prime_central = central_difference(x,y)\r\n\r\nplt.figure()\r\nplt.plot(x[1:-1],y_prime_central)\r\nplt.grid(1)\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.savefig('sin_prime_central(x).png')\r\n\r\ndef complete_prime(x,y):\t\t\t\r\n\th = (max(x)-min(x))/float(len(x)-1)\r\n\tprime_0 = float(y[1]-y[0])/float(h)\r\n\tprime_last = float(y[-1]-y[-2])/float(h)\r\n\tprime = (y[2:]-y[0:-2])/float(2*h)\r\n\tcomplete_prime = np.concatenate([[prime_0],prime,[prime_last]])\r\n\treturn complete_prime\r\n\r\nprint('Error associated with forward difference: ' + str(np.sum(np.square(np.subtract(y_prime[:-1],y_prime_forward))))) #Mean squared error\r\nprint('Error associated with backward difference: ' + str(np.sum(np.square(np.subtract(y_prime[1:],y_prime_backward)))))\r\nprint('Error associated with central difference: ' + str(np.sum(np.square(np.subtract(y_prime[1:-1],y_prime_central)))))\r\nprint('Error associated with complete difference: ' + str(np.sum(np.square(np.subtract(y_prime,complete_prime(x,y))))))\r\nprint('\\n')\r\n\r\n########### Integration ##################\r\n\r\nfrom scipy import integrate\r\n\r\nprint('Integration')\r\nprint('\\n')\r\n\r\ndef int_trap(x,y):\r\n\th = (max(x)-min(x))/float(len(x)-1)\r\n\ty *= h\r\n\tintegral = np.sum(y[1:-1]) + ((y[0]+y[-1])/2.0)\r\n\treturn integral\r\n\r\ntrapezoids = int_trap(x,fun(x))\r\ntrapezoids_scipy = integrate.trapz(fun(x), x)\r\n\r\nprint('Integral of sin(x)[0,pi] using trapezoids:' + '\\n' + 'Using our implementation: ' + str(trapezoids) + '\\n' 'Using SciPy: ' +str(trapezoids_scipy))\r\nprint('\\n')\r\n\r\nx_simp = np.linspace(0,np.pi,1001)\r\n\r\ndef int_simpson(x,y):\r\n\th = (max(x)-min(x))/float(len(x)-1)\r\n\ty *= h\r\n\tintegral = np.sum(y[1:-1:2]*4.0/3.0) + np.sum(y[2:-2:2]*2.0/3.0) + ((y[0]+y[-1])/3.0)\r\n\treturn integral\r\n\r\nsimpson = int_simpson(x_simp,fun(x_simp))\r\nsimpson_scipy = integrate.simps(fun(x_simp), x_simp)\r\n\r\nprint('Integral of sin(x)[0,pi] using Simpson\\'s Method:' + '\\n' + 'Using our implementation: ' + str(simpson) + '\\n' 'Using SciPy: ' + str(simpson_scipy))\r\nprint('\\n')\r\n\r\nx_mc = np.linspace(0,2*np.pi,1000)\r\ny_mc = fun(x_mc)\r\ny_random = np.random.uniform(-1,1,1000)\r\nplt.figure()\r\nplt.scatter(x_mc,y_random)\r\nplt.plot(x_mc,y_mc,c='r')\r\nplt.plot(x_mc,np.zeros(len(x)),c='b')\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.grid(1)\r\nplt.savefig('monte_carlo.png')\r\n\r\ndef int_mc(x_min,x_max,y,N):\r\n\tcounter = []\r\n\ty_max = max(y)\r\n\ty_min = min(y)\r\n\tarea = (x_max-x_min)*(y_max-y_min)\r\n\ty_ran = np.random.uniform(y_min,y_max,N)\r\n\tfor i in range(N):\r\n\t\tif(y_ran[i]>0 and y[i]>0 and abs(y_ran[i])<=abs(y[i])):\r\n\t\t\tcounter.append(1)\r\n\t\telif(y_ran[i]<0 and y[i]<0 and abs(y_ran[i])<=abs(y[i])):\r\n\t\t\tcounter.append(-1)\r\n\t\telse:\r\n\t\t\tcounter.append(0)\r\n\treturn (np.mean(counter)*area)\r\n\r\nmonte_carlo_1000 = int_mc(0,np.pi,fun(np.random.uniform(0,2*np.pi,1000)),1000)\r\nmonte_carlo_10000 = int_mc(0,np.pi,fun(np.random.uniform(0,2*np.pi,10000)),10000)\r\nmonte_carlo_100000 = int_mc(0,np.pi,fun(np.random.uniform(0,2*np.pi,100000)),100000)\r\n\r\nprint('Integral of sin(x)[0,2pi] using Monte Carlo\\'s Method:' + '\\n' + 'Using 1000 points: ' + str(monte_carlo_1000) + '\\n' 'Using 10000 points: ' + str(monte_carlo_10000) + '\\n' 'Using 100000 points: ' + str(monte_carlo_100000))\r\nprint('\\n')\r\n\r\n########### Filters ##################\r\n\r\nfrom scipy.fftpack import fft, ifft, fftfreq\r\nfrom scipy import signal\r\n\r\nour_signal = np.genfromtxt('signal.dat', delimiter = ',')\r\n\r\nsignal_x = our_signal[:,0]\r\nsignal_y = our_signal[:,1]\r\n\r\nplt.figure()\r\nplt.plot(signal_x,signal_y)\r\nplt.xlabel('$x$')\r\nplt.ylabel('$y$')\r\nplt.grid(1)\r\nplt.savefig('noisy_signal.png')\r\n\r\nfourier_transform = np.real(fft(signal_y))\r\nfrequencies = fftfreq(len(signal_x),signal_x[1]-signal_x[0])\r\n\r\nplt.figure()\r\nplt.plot(frequencies,fourier_transform)\r\nplt.xlabel('$f$')\r\nplt.ylabel('Amplitude')\r\nplt.grid(1)\r\nplt.savefig('fourier_transform.png')\r\n\r\ndef filter_lowpass(frequencies,transform,n):\r\n\tfor i in range(0,len(frequencies)):\r\n\t\tif abs(frequencies[i])>n:\r\n\t\t\ttransform[i] = 0\r\n\r\n\treturn transform\r\n\r\ndef filter_highpass(frequencies,transform,n):\r\n\tfor i in range(0,len(frequencies)):\r\n\t\tif abs(frequencies[i])= tol:\n k += 1\n x = A @ eigv\n eig = x[np.argmax(x)]\n eigv = x / eig\n\n return k, eig, eigv\n\n\ndef acceleration_power_method(A, alpha, tol=1e-9, Max_iter=100):\n \"\"\" Calculate maximum eigenvalue of matrix A by origin translation acceration power method.\n\n Args:\n A: ndarray, the matrix to be solved\n alpha: double, acceleration parameter\n tol: double, iteration accuracy\n Max_iter: int, maximum iteration number\n\n Returns:\n k: int, iteration number\n eig: double, main eigenvalue(maximum) of matrix A\n eigv: ndarray, corresponding eigenvector\n \"\"\"\n # initialization\n B = A - alpha * np.eye(A.shape[0])\n \n # power method\n k, eig, eigv = power_method(B, np.ones(A.shape[0]), tol, Max_iter)\n\n eig += alpha\n\n return k, eig, eigv\n\n\nif __name__ == '__main__':\n A = np.array([[4, -1, 1], [-1, 3, -2], [1, -2, 3]])\n # power method\n ini_vecs = [[1, 1, 1], [2.001, 1.999, 0], [0, 1, 1]]\n for ini_vec in ini_vecs:\n n, eig, eigv = power_method(A, ini_vec, 1e-6)\n print(f\"When selecting the initial values {ini_vec},\") \n print(f\"main eigenvalue is {eig:.7f}, corresponding eigenvector is {eigv},\") \n print(f\"the iteration number is {n}.\")\n\n # acceleration power method\n alpha_lst = np.linspace(1, 3, 5)\n for alpha in alpha_lst:\n n, eig, eigv = acceleration_power_method(A, alpha, 1e-6)\n print(f\"Whene selection the parameter alpha = {alpha},\")\n print(f\"main eigenvaluue is {eig:.7f}, corresponding eigenvector is {eigv},\")\n print(f\"the iteration number is {n}\")\n\n", "meta": {"hexsha": "c733c675f3209fb38558323a835d44d2b9517cfa", "size": 2366, "ext": "py", "lang": "Python", "max_stars_repo_path": "EigenvaluesandEigenvectors/power_method.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EigenvaluesandEigenvectors/power_method.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenvaluesandEigenvectors/power_method.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9493670886, "max_line_length": 95, "alphanum_fraction": 0.6145393068, "include": true, "reason": "import numpy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843811, "lm_q2_score": 0.955981347315302, "lm_q1q2_score": 0.9157462644770888}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nfrom scipy.stats import norm\n\n\n## Gaussians\ndef gaussian_density(x, mu, sigma):\n return (1/np.sqrt(2*np.pi*np.power(sigma, 2.))) * np.exp(-np.power(x - mu, 2.) / (2 * np.power(sigma, 2.)))\n\ndef gaussian_probability(mean, stdev, x_low, x_high):\n return norm(loc = mean, scale = stdev).cdf(x_high) - norm(loc = mean, scale = stdev).cdf(x_low)\n\ndef plot_gaussian(x, mu, sigma):\n\n # y = gaussian_density(x, mu, sigma)\n y = mlab.normpdf(x,mu,sigma)\n plt.plot(x, y)\n plt.title('Gaussian Probability Density Function')\n plt.xlabel('x variable')\n plt.ylabel('probability density function')\n plt.show()\n\ndef plot_gaussian2(x, mu1, sigma1,mu2,sigma2):\n\n # y = gaussian_density(x, mu, sigma)\n y1 = norm.pdf(x,mu1,sigma1)\n y2 = norm.pdf(x,mu2,sigma2)\n plt.plot(x, y1,'b')\n plt.plot(x, y2,'r--')\n # y3 = y1*y2\n # y3 = ((y1.sum() + y2.sum()) / 2.0) * (y3.astype(float) / y3.astype(float).sum())\n \n # plt.plot(x, y3,'r--')\n plt.title('Gaussian Probability Density Function')\n plt.xlabel('x variable')\n plt.ylabel('probability density function')\n plt.show()\n\n\n# mu1 = 120\n# mu2 = 200\n# sigma1 = 40\n# sigma2 = 20\n# x = np.linspace(1,280,1000)\n# plot_gaussian2(x,mu1,sigma1,mu2,sigma2)\n\n\n\n\n", "meta": {"hexsha": "cdc1cfee34753fb82b8bef75564e67e01d9b5ddc", "size": 1320, "ext": "py", "lang": "Python", "max_stars_repo_path": "self-driving/Matrix/gaussian.py", "max_stars_repo_name": "xta0/Python-Playground", "max_stars_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "self-driving/Matrix/gaussian.py", "max_issues_repo_name": "xta0/Python-Playground", "max_issues_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "self-driving/Matrix/gaussian.py", "max_forks_repo_name": "xta0/Python-Playground", "max_forks_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8823529412, "max_line_length": 111, "alphanum_fraction": 0.6363636364, "include": true, "reason": "import numpy,from scipy", "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9859363733699887, "lm_q2_score": 0.9284088035267047, "lm_q1q2_score": 0.9153520087538897}} {"text": "import sys\nimport numpy as np\nfrom numpy import pi\n\na = np.arange(15).reshape(3, 5) # Create array 3x5 of integers from 0 to 14\nprint(a) # It is a 2-d array\nprint(a.shape) # A tuple of the dimensions of the array: (3, 5)\nprint(a.ndim) # An integer representing the number of dimensions: 2\nprint(a.dtype.name) # A string representing the name of the variables in the array: int32\nprint(a.itemsize) # An integer = 32 / 8 = 4\nprint(a.size) # An integer representing the size of the array: 15\nprint(type(a)) # A string representing the class of the array: \"\"\n\n# Creation of the array\nprint(\"\\narray\\n\")\n\nprint(np.array([2, 3, 4])) # Create numpy array of int64 from Python list\nprint(np.array([1.2, 3.5, 5.1])) # Array of float64\nprint(np.array([(1.5, 2, 3), (4, 5, 6)])) # 2-d array from sequence of sequences\nprint(np.array([[1, 2], [3, 4]], dtype=complex)) # Explicitly specify a type of the array during creation (complex)\nprint(np.zeros((3, 4))) # Create an array 3x4 filled with zeroes\nprint(np.ones((2, 3, 4), dtype=np.int16)) # Create an array of int16 2x3x4 filled with ones\nprint(np.empty((2, 3))) # Create an array 2x3 filled with random data\n\n# Creation of ranges with arange\nprint(\"\\narange\\n\")\n\nprint(np.arange(10, 30, 5)) # Same as range(10, 30, 5) in Python, byt returns array\nprint(np.arange(0, 2, 0.3)) # It accepts float arguments\n\n# Creation of ranges with linspace\nprint(\"\\nlinspace\\n\")\n\nprint(np.linspace(0, 2, 9)) # 9 numbers from 0 to 2\nx = np.linspace(0, 2 * pi, 100) # Useful to evaluate function at lots of points\nprint(np.sin(x))\n\n# Printing arrays\nprint(\"\\nPrinting arrays\\n\")\n\nprint(np.arange(6)) # 1d array looks as a row\nprint(np.arange(12).reshape(4, 3)) # 2d array looks as a matrix\nprint(np.arange(24).reshape(2, 3, 4)) # 3d array looks as a list of matrices\n\nprint(np.arange(10000)) # NumPy automatically skips the central part of the array and only prints the corners\nprint(np.arange(10000).reshape(100, 100))\n\n# Basic Operations\nprint(\"\\nBasic Operations\\n\")\n\na = np.array([20, 30, 40, 50])\nb = np.arange(4)\nprint(b) # array([0, 1, 2, 3])\nprint(a - b) # array([20, 29, 38, 47])\nprint(b**2) # array([0, 1, 4, 9])\nprint(10 * np.sin(a)) # array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])\nprint(a < 35) # array([ True, True, False, False])\n\n# Matrices multiplication\nprint(\"\\nMatrices multiplication\\n\")\n\nA = np.array([[1, 1],\n [0, 1]])\nB = np.array([[2, 0],\n [3, 4]])\nprint(A * B) # elementwise product: array([[2, 0], [0, 4]])\nprint(A @ B) # matrix product: array([[5, 4], [3, 4]])\nprint(A.dot(B)) # another matrix product: array([[5, 4], [3, 4]])\n\n# +=\n\nprint(\"\\n+=\\n\")\nrg = np.random.default_rng(1) # create instance of default random number generator\na = np.ones((2, 3), dtype=int)\nb = rg.random((2, 3))\na *= 3\nprint(a) # array([[3, 3, 3], [3, 3, 3]])\nb += a\nprint(b) # array([[3.51182162, 3.9504637 , 3.14415961], [3.94864945, 3.31183145, 3.42332645]])\ntry:\n a += b # b is not automatically converted to integer type\nexcept Exception as e:\n print(e)\n\n# When operating with arrays of different types, the type of the resulting array corresponds\n# to the more general or precise one (a behavior known as upcasting).\n\nprint(\"\\nUpcasting\\n\")\na = np.ones(3, dtype=np.int32)\nb = np.linspace(0, pi, 3)\nprint(b.dtype.name) # 'float64'\nc = a + b # Trying to sum int with float\nprint(c) # array([1. , 2.57079633, 4.14159265])\nprint(c.dtype.name) # 'float64'\nd = np.exp(c * 1j) # Creating array of complexes\nprint(d) # array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j, -0.54030231-0.84147098j])\nprint(d.dtype.name) # 'complex128'\n\n# Unary operators\nprint(\"\\nUnary operators\\n\")\n\na = rg.random((2, 3))\nprint(a) # array([[0.82770259, 0.40919914, 0.54959369], [0.02755911, 0.75351311, 0.53814331]])\nprint(a.sum()) # 3.1057109529998157\nprint(a.min()) # 0.027559113243068367\nprint(a.max()) # 0.8277025938204418\n\n# By default, these operations apply to the array as though it were a list of numbers, regardless of its shape.\n# However, by specifying the axis parameter you can apply an operation along the specified axis of an array:\nprint(\"\\nAxis operators\\n\")\n\nb = np.arange(12).reshape(3, 4)\nprint(b)\n\"\"\"array([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\"\"\"\nprint(b.sum(axis=0)) # sum of each column: array([12, 15, 18, 21])\nprint(b.min(axis=1)) # min of each row: array([0, 4, 8])\nprint(b.cumsum(axis=1)) # cumulative sum along each row\n\"\"\"array([[ 0, 1, 3, 6],\n [ 4, 9, 15, 22],\n [ 8, 17, 27, 38]])\"\"\"\n\n# Universal functions\n\"\"\"NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal \nfunctions” (ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output.\"\"\"\nprint(\"\\nUniversal functions\\n\")\n\nB = np.arange(3)\nprint(B) # array([0, 1, 2])\nprint(np.exp(B)) # array([1. , 2.71828183, 7.3890561 ])\nprint(np.sqrt(B)) # array([0. , 1. , 1.41421356])\nC = np.array([2., -1., 4.])\nprint(np.add(B, C)) # array([2., 0., 6.])\n\n# Indexing, Slicing and Iterating\n\"\"\"One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.\"\"\"\nprint(\"\\nIndexing, Slicing and Iterating\\n\")\n\na = np.arange(10)**3\nprint(a) # array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])\nprint(a[2]) # Get by index: 8\nprint(a[2:5]) # Get slice : array([ 8, 27, 64])\n# equivalent to a[0:6:2] = 1000;\n# from start to position 6, exclusive, set every 2nd element to 1000\na[:6:2] = 1000\nprint(a) # array([1000, 1, 1000, 27, 1000, 125, 216, 343, 512, 729])\nprint(a[::-1]) # reversed a: array([ 729, 512, 343, 216, 125, 1000, 27, 1000, 1, 1000])\nfor i in a:\n print(i**(1 / 3.))\n\n\"\"\"9.999999999999998\n1.0\n9.999999999999998\n3.0\n9.999999999999998\n4.999999999999999\n5.999999999999999\n6.999999999999999\n7.999999999999999\n8.999999999999998\"\"\"\n\n# Indices\n\"\"\"Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas:\"\"\"\nprint(\"\\nIndices\\n\")\n\n\ndef f(x, y):\n return 10 * x + y # Will it use as lambda function\n\n\nb = np.fromfunction(f, (5, 4), dtype=int) # Construct an array by indexing the function\nprint(b)\n\"\"\"array([[ 0, 1, 2, 3],\n [10, 11, 12, 13],\n [20, 21, 22, 23],\n [30, 31, 32, 33],\n [40, 41, 42, 43]])\"\"\"\nprint(b[2, 3]) # 23\nprint(b[0:5, 1]) # each row in the second column of b: array([ 1, 11, 21, 31, 41])\nprint(b[:, 1]) # equivalent to the previous example: array([ 1, 11, 21, 31, 41])\nprint(b[1:3, :]) # each column in the second and third row of b\n\"\"\"array([[10, 11, 12, 13],\n [20, 21, 22, 23]])\"\"\"\n\n# Autocompletion\n\"\"\"When fewer indices are provided than the number of axes, the missing indices are considered complete slices:\"\"\"\nprint(\"\\nAutocompletion\\n\")\n\nprint(b[-1]) # the last row. Equivalent to b[-1, :] : array([40, 41, 42, 43])\n\n\"\"\"The dots (...) represent as many colons as needed to produce a complete indexing tuple\"\"\"\nc = np.array([[[ 0, 1, 2], # a 3D array (two stacked 2D arrays)\n [ 10, 12, 13]],\n [[100, 101, 102],\n [110, 112, 113]]])\nprint(c.shape) # (2, 2, 3)\nprint(c[1, ...]) # same as c[1, :, :] or c[1]\n\"\"\"array([[100, 101, 102],\n [110, 112, 113]])\"\"\"\nprint(c[..., 2]) # same as c[:, :, 2]:\n\"\"\"array([[ 2, 13],\n [102, 113]])\"\"\"\n\n# Iterating over multidimensional arrays is done with respect to the first axis:\nprint(\"\\nIterating over multidimensional arrays\\n\")\n\nfor row in b:\n print(row)\n\n\"\"\"[0 1 2 3]\n[10 11 12 13]\n[20 21 22 23]\n[30 31 32 33]\n[40 41 42 43]\"\"\"\n\n# However, if one wants to perform an operation on each element in the array,\n# one can use the flat attribute which is an iterator over all the elements of the array:\n\nfor element in b.flat:\n print(element) # 0 1 2 3\n\n\n", "meta": {"hexsha": "12652bd584c89ed7adb8b1acc542a6e1e1cdbb1d", "size": 7945, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy-education-project/01-quickstart/01-the-basics.py", "max_stars_repo_name": "IvanDemin3467/numpy-education-project", "max_stars_repo_head_hexsha": "9434be4d6f97c241f4732359a7a2aeea982cc499", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy-education-project/01-quickstart/01-the-basics.py", "max_issues_repo_name": "IvanDemin3467/numpy-education-project", "max_issues_repo_head_hexsha": "9434be4d6f97c241f4732359a7a2aeea982cc499", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy-education-project/01-quickstart/01-the-basics.py", "max_forks_repo_name": "IvanDemin3467/numpy-education-project", "max_forks_repo_head_hexsha": "9434be4d6f97c241f4732359a7a2aeea982cc499", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.46875, "max_line_length": 116, "alphanum_fraction": 0.6339836375, "include": true, "reason": "import numpy,from numpy", "num_tokens": 2839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.9572778023011562, "lm_q1q2_score": 0.9151397234990241}} {"text": "\"\"\"Largest prime factor\n\nThe prime factors of 13195 are 5, 7, 13 and 29.\nWhat is the largest prime factor of the number 600851475143?\n\"\"\"\n\nimport math\nimport numpy as np\n\n\ndef largest_prime_factor_naive(number):\n \"\"\"\n Let the given number be n and let k = 2, 3, 4, 5, ... .\n\n For each k, if it is a factor of n then we divide n by k and completely divide out each k before moving to the next k.\n\n It can be seen that when k is a factor it will necessarily be prime, as all smaller factors have been removed,\n and the final result of this process will be n = 1.\n \"\"\"\n factor = 2\n factors = []\n while number > 1:\n if number % factor == 0:\n factors.append(factor)\n number = number // factor # Remainder guarenteed to be zero\n while number % factor == 0:\n number = number // factor # Remainder guarenteed to be zero\n factor += 1\n return factors\n\n\ndef largest_prime_factor_even_optimized(number):\n \"\"\"\n We know that, excluding 2, there are no even prime numbers.\n So we can increase factor by 2 per iteration after having found the \n \"\"\"\n factors = []\n factor = 2\n if number % factor == 0:\n number = number // factor\n factors.append(factor)\n while number % factor == 0:\n number = number // factor\n\n factor = 3\n while number > 1:\n if number % factor == 0:\n factors.append(factor)\n number = number // factor # Remainder guarenteed to be zero\n while number % factor == 0:\n number = number // factor # Remainder guarenteed to be zero\n factor += 2\n return factors\n\n\ndef largest_prime_factor_square_optimized(number):\n \"\"\"\n Every number n can at most have one prime factor greater than n.\n\n If we, after dividing out some prime factor, calculate the square root of the remaining number\n we can use that square root as upper limit for factor.\n \n If factor exceeds this square root we know the remaining number is prime.\n \"\"\"\n factors = []\n factor = 2\n if number % factor == 0:\n number = number // factor\n factors.append(factor)\n while number % factor == 0:\n number = number // factor\n\n factor = 3\n max_factor = math.sqrt(number)\n while number > 1 and factor <= max_factor:\n if number % factor == 0:\n factors.append(factor)\n number = number // factor\n while number % factor == 0:\n number = number // factor\n max_factor = math.sqrt(number)\n factor += 2\n\n return factors\n\n\ndef idx_sieve(length):\n \"\"\"Static length sieve-based prime generator\"\"\"\n primes = []\n is_prime = np.array([True]*length)\n i = 2\n while i < length:\n if is_prime[i]:\n is_prime[np.arange(i, length, i)] = False\n primes.append(i)\n else:\n i += 1\n return primes\n\n\ndef prime_factor(n, primes):\n i = 0\n factors = []\n while n != 1:\n while (n % primes[i]) != 0:\n i += 1\n factors.append(primes[i])\n n = n / primes[i]\n return factors\n\n\nif __name__ == '__main__':\n number = 600851475143\n print(largest_prime_factor_naive(number))\n print(largest_prime_factor_even_optimized(number))\n print(largest_prime_factor_square_optimized(number))\n\n number = 600851475143\n primes = idx_sieve(20000)\n \n print(max(prime_factor(number, primes)))\n", "meta": {"hexsha": "0b610800704e8c840fbc0a2a516adbeed8570f93", "size": 3479, "ext": "py", "lang": "Python", "max_stars_repo_path": "problems/problem3.py", "max_stars_repo_name": "JakobHavtorn/euler", "max_stars_repo_head_hexsha": "b5ca0b4393dc9a6d6e0623e0df5b96f803e116ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/problem3.py", "max_issues_repo_name": "JakobHavtorn/euler", "max_issues_repo_head_hexsha": "b5ca0b4393dc9a6d6e0623e0df5b96f803e116ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/problem3.py", "max_forks_repo_name": "JakobHavtorn/euler", "max_forks_repo_head_hexsha": "b5ca0b4393dc9a6d6e0623e0df5b96f803e116ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5163934426, "max_line_length": 122, "alphanum_fraction": 0.6033342915, "include": true, "reason": "import numpy", "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812309063186, "lm_q2_score": 0.9449947068655582, "lm_q1q2_score": 0.915115137434425}} {"text": "# Optimize a polynomial function to find minima/maxima using 2nd order Newton's method.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pprint import pprint\n\n# Function is: f(x) = 6x^5 - 5x^4 - 4x^3 + 3x^2\n\ndef f(x):\n return 6*x**5-5*x**4-4*x**3+3*x**2\n\ndef df(x):\n return 30*x**4-20*x**3-12*x**2+6*x\n\ndef d2f(x):\n return 120*x**3-60*x**2-24*x+6\n\ndef delta_fn(x):\n return abs(f(x)-0)\n\ndef newton_root_finding(x0, epsilon):\n # Finding root of a function using Newton's Method\n\n x_root = np.zeros(len(x0))\n for i, x in enumerate(x0):\n delta = delta_fn(x)\n while delta > epsilon:\n x = x - f(x) / float(df(x))\n delta = delta_fn(x)\n x_root[i] = x\n\n return list(x_root)\n\ndef newton_optimization(x1, epsilon):\n # Finding minima/maxima using Newton's Method\n\n x_critical = np.zeros(len(x1))\n minmax = {}\n\n for i, x in enumerate(x1):\n n = 0\n delta = delta_fn(x)\n\n while delta > epsilon:\n x = x - df(x) / float(d2f(x))\n delta = delta_fn(x)\n n += 1\n if n == 10000:\n break\n x_critical[i] = x\n print \"\\nCritical points: \"\n pprint(list(x_critical))\n\n for x in x_critical:\n if d2f(x) > 0:\n minmax[x] = 'minima'\n elif d2f(x) < 0:\n minmax[x] = 'maxima'\n elif d2f(x) == 0:\n minmax[x] = 'saddle'\n\n return minmax\n\ndef plot_graph():\n x_points = np.arange(-0.8,1.1,0.01)\n fn_points = [f(x) for x in x_points]\n plt.plot(x_points, fn_points, 'ro')\n plt.show()\n\n\ndef main():\n epsilon = 1e-10\n x0 = [-1, 0, 0.5, 1]\n\n x_root = newton_root_finding(x0,epsilon)\n print \"\\nRoots are: \"\n pprint(x_root)\n\n x1 = [-0.5, 0.1, 0.5, 1.5, 3]\n minmax = newton_optimization(x1, epsilon)\n print \"\\nMinima/Maxima points are: \"\n pprint(minmax)\n\n plot_graph()\n\nif __name__ == '__main__':\n main()\n\n\n'''\nResult-\nRoots are: \n[-0.7953336454431276, 0.0, 0.6286669787778999, 1.0]\n\nCritical points: \n[-0.5889879839687899,\n -8.969446052179515e-10,\n 0.39415736752083946,\n 0.8614972831146172,\n 0.861497283114617]\n\nMinima/Maxima points are: \n{-0.5889879839687899: 'maxima',\n -8.969446052179515e-10: 'minima',\n 0.39415736752083946: 'maxima',\n 0.861497283114617: 'minima',\n 0.8614972831146172: 'minima'}\n'''", "meta": {"hexsha": "e6726c9621517156087e52584f450124b128c4d6", "size": 2335, "ext": "py", "lang": "Python", "max_stars_repo_path": "Second_order_optimization_Newtons_Method/mycode_optimization.py", "max_stars_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_stars_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second_order_optimization_Newtons_Method/mycode_optimization.py", "max_issues_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_issues_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second_order_optimization_Newtons_Method/mycode_optimization.py", "max_forks_repo_name": "DillipKS/The-Math-of-Intelligence-course", "max_forks_repo_head_hexsha": "fc0f33e638fdbd05e93d54d38ed8493808f6ec74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-08T07:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-08T07:58:13.000Z", "avg_line_length": 21.6203703704, "max_line_length": 87, "alphanum_fraction": 0.5850107066, "include": true, "reason": "import numpy", "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105287006256, "lm_q2_score": 0.9372107861416413, "lm_q1q2_score": 0.9150087581218748}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n#Continuous Uniform Distribution\ndef probability_uniform(low_range, high_range, minimum, maximum):\n\n if( isinstance(low_range,str) or \n isinstance(high_range,str) or \n isinstance(minimum,str) or \n isinstance(maximum,str)):\n \n print('Inputs should be numbers not string')\n return None\n \n if (low_range < minimum or low_range > maximum):\n print('Your low range value must be between minimum and maximum')\n return None\n \n\n if (high_range < minimum or high_range > maximum):\n print('The high range value must be between minimum and maximum')\n return None\n\n probability = abs(high_range-low_range)/abs(maximum-minimum)\n return probability\n\n## Gaussians\ndef gaussian_density(x, mu, sigma):\n return (1/np.sqrt(2*np.pi*np.power(sigma, 2.))) * np.exp(-np.power(x - mu, 2.) / (2 * np.power(sigma, 2.)))\n\n\ndef plot_gaussian(x, mu, sigma):\n\n y = gaussian_density(x, mu, sigma)\n\n plt.plot(x, y)\n plt.title('Gaussian Probability Density Function')\n plt.xlabel('x variable')\n plt.ylabel('probability density function')\n plt.show()\n\n#Calculating Area Under the Curve in Python\nfrom scipy.stats import norm\n\nprint(gaussian_density(50, 50, 10))\n#using scipy\nprint(norm(loc = 50, scale = 10).pdf(50))\n\n#Calculating Area Under the Curve Solution\ndef gaussian_probability(mean, stdev, x_low, x_high):\n return norm(loc = mean, scale = stdev).cdf(x_high) - norm(loc = mean, scale = stdev).cdf(x_low)\n\n", "meta": {"hexsha": "238168e34829a38dd614d3fa8171114c5c88a55b", "size": 1549, "ext": "py", "lang": "Python", "max_stars_repo_path": "self-driving/Bayesian/distributions.py", "max_stars_repo_name": "xta0/Python-Playground", "max_stars_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "self-driving/Bayesian/distributions.py", "max_issues_repo_name": "xta0/Python-Playground", "max_issues_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "self-driving/Bayesian/distributions.py", "max_forks_repo_name": "xta0/Python-Playground", "max_forks_repo_head_hexsha": "513ebd2ad7f0a8c69f2f04b4f7524b31e76fa5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2264150943, "max_line_length": 111, "alphanum_fraction": 0.6797934151, "include": true, "reason": "import numpy,from scipy", "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692311915196, "lm_q2_score": 0.9362850013033613, "lm_q1q2_score": 0.9144407523991048}} {"text": "import numpy as np\n\ndef integrate_rec(f, a, b, n):\n # Implementation of the rectanlge method \n h = (b-a)/n\n x = np.linspace(a, b, n+1) \n i=0\n area=0\n while i 1e-3)\n plt.plot(w[ii], np.unwrap(np.angle(Y[ii])), \"go\", lw=2)\n plt.xlim(-lim, lim)\n plt.grid(True)\n\n plt.savefig(\"Assignment_08/LaTeX/\" + out)\n\n\nx = np.linspace(0, 2 * np.pi, 128, endpoint=False)\nw = np.linspace(-64, 64, 128, endpoint=False)\n\nY = fftshift(fft(np.sin(5 * x))) / 128\nplotter(w, Y, \"Spectrum of $\\sin(5t)$\", 10, \"eg2\", \"$k$\")\n\nY = fftshift(fft((1 + 0.1 * np.cos(x)) * np.cos(10 * x))) / 128\nplotter(w, Y, \"Spectrum of $(1 + 0.1\\cos(t))\\cdot\\cos(10t)$\", 15, \"eg3\")\n\n\nx = np.linspace(-4 * np.pi, 4 * np.pi, 512, endpoint=False)\nw = np.linspace(-64, 64, 512, endpoint=False)\n\nY = fftshift(fft((1 + 0.1 * np.cos(x)) * np.cos(10 * x))) / 512\nplotter(w, Y, \"Spectrum of $(1 + 0.1\\cos(t))\\cdot\\cos(10t)$ (Improved)\", 15, \"eg4\")\n\nY = fftshift(fft(np.sin(x) ** 3)) / 512\nplotter(w, Y, \"Spectrum of $\\sin^3(t)$\", 15, \"q2a\")\n\nY = fftshift(fft(np.cos(x) ** 3)) / 512\nplotter(w, Y, \"Spectrum of $\\cos^3(t)$\", 15, \"q2b\")\n\nY = fftshift(fft(np.cos(20 * x + 5 * np.cos(x)))) / 512\nplotter(w, Y, \"Spectrum of $\\cos(20t + 5\\cos(t))$\", 30, \"q3\")\n\n\nT = 2 * np.pi\nN = 128\niter_n = 0\nerror = None\nthreshold = 1e-6 # 6 decimals of precision\n\nwhile error is None or error > threshold:\n t = np.linspace(-T / 2, T / 2, N, endpoint=False)\n w = np.linspace(-np.pi, np.pi, N, endpoint=False) * N / T\n y = np.exp(-0.5 * t ** 2)\n Y = fftshift(fft(ifftshift(y))) * T / (2 * np.pi * N)\n\n Y_true = np.exp(-0.5 * w ** 2) / np.sqrt(2 * np.pi)\n error = np.max(np.abs(Y - Y_true))\n\n T *= 2\n N *= 2\n iter_n += 1\n print(f\"Iteration {iter_n}: Total Error = {error:.2e}\")\n\nT /= 2\nN /= 2\n\nprint(f\"Samples = {int(N)}, Time Period = {int(T / np.pi)} pi\")\n\nplotter(w, Y, \"Spectrum of Approximated Gaussian\", 5, \"q4a\")\nplotter(w, Y_true, \"Spectrum of True Gaussian\", 5, \"q4b\")\n\n\nplt.show()\n", "meta": {"hexsha": "f90ec8f65005cd3d550d5606991fba54fea66a28", "size": 2839, "ext": "py", "lang": "Python", "max_stars_repo_path": "Assignment_08/DFT.py", "max_stars_repo_name": "sohamroy19/EE2703", "max_stars_repo_head_hexsha": "7ea141082815d80fe765344303d98f96f7a9a492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment_08/DFT.py", "max_issues_repo_name": "sohamroy19/EE2703", "max_issues_repo_head_hexsha": "7ea141082815d80fe765344303d98f96f7a9a492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment_08/DFT.py", "max_forks_repo_name": "sohamroy19/EE2703", "max_forks_repo_head_hexsha": "7ea141082815d80fe765344303d98f96f7a9a492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0458715596, "max_line_length": 88, "alphanum_fraction": 0.5857696372, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.9465966737782309, "lm_q1q2_score": 0.9138265941973728}} {"text": "# Author: OMKAR PATHAK\n\n# This program illustrates how to create an adarray from numerical ranges\n\nimport numpy as np\n\n# ndarray.arange(start, stop, step, dtype)\n# Creates a numpy array from 1 to 20\nmyArray = np.arange(1, 21)\nprint(myArray) # [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]\n\n# Specifying data type of each element\nmyArray = np.arange(10, dtype = 'float')\nprint(myArray) # [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]\n\n# Specifying steps to jump in between two elements\nmyArray = np.arange(1, 21, 2)\nprint(myArray) # [ 1  3  5  7  9 11 13 15 17 19]\n\n# ndarray.linspace(start, stop, num, endpoint, retstep, dtype)\n# Shows 5 equal intervals between 10 to 20\nmyArray = np.linspace(10, 20, 5)\nprint(myArray) # [ 10.   12.5  15.   17.5  20. ]\n\n# if endpoint is set to false the last number inn STOP parameter is not executed\nmyArray = np.linspace(10, 20, 5, endpoint = False)\nprint(myArray) # [ 10.  12.  14.  16.  18.]\n\n# ndarray.lopspace returns an ndarray object that contains the numbers that are evenly spaced\n# on a log scale.\n# ndarray.logscale(start, stop, num, endpoint, base, dtype)\n# default base is 10\nmyArray = np.logspace(1.0, 3.0, num = 10)\nprint(myArray)\n\n# [   10.            16.68100537    27.82559402    46.41588834    77.42636827\n#    129.1549665    215.443469     359.38136638   599.48425032  1000.        ]\n\nmyArray = np.logspace(1.0, 3.0, num = 10, base = 2)\nprint(myArray)\n\n# [ 2.          2.33305808  2.72158     3.1748021   3.70349885  4.32023896\n#   5.0396842   5.87893797  6.85795186  8.        ]\n", "meta": {"hexsha": "e8dbbf554cda19214b6a66f9b788c6afea7425be", "size": 1653, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python-Programs/Numpy/P04_ArrayFromNumericalRanges.py", "max_stars_repo_name": "shubhamnag14/python-examples", "max_stars_repo_head_hexsha": "4dc9227095ed8e91b3c6b18b6f7a81ae60eb6306", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python-Programs/Numpy/P04_ArrayFromNumericalRanges.py", "max_issues_repo_name": "shubhamnag14/python-examples", "max_issues_repo_head_hexsha": "4dc9227095ed8e91b3c6b18b6f7a81ae60eb6306", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python-Programs/Numpy/P04_ArrayFromNumericalRanges.py", "max_forks_repo_name": "shubhamnag14/python-examples", "max_forks_repo_head_hexsha": "4dc9227095ed8e91b3c6b18b6f7a81ae60eb6306", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-12T13:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-12T13:32:45.000Z", "avg_line_length": 37.5681818182, "max_line_length": 99, "alphanum_fraction": 0.611615245, "include": true, "reason": "import numpy", "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750466836961, "lm_q2_score": 0.9585377226988919, "lm_q1q2_score": 0.91375009235387}} {"text": "import numpy as np\n#Creation of Evenly Spaced Values\nimport numpy as np\na = np.arange(1, 10)\nprint(a)\n# compare to range:\nx = range(1,10)\nprint(x) # x is an iterator\nprint(list(x))\n# some more arange examples:\nx = np.arange(10.4)\nprint(x)\nx = np.arange(0.5, 10.4, 0.8)\nprint(x)\nx = np.arange(0.5, 10.4, 0.8, int)\nprint(x)\n# 50 values between 1 and 10:\nprint(np.linspace(1, 10))\n# 7 values between 1 and 10:\nprint(np.linspace(1, 10, 7))\n# excluding the endpoint:\nprint(np.linspace(1, 10, 7, endpoint=False))\n\"\"\" \nThe syntax of arange:\n\narange([start,] stop[, step,], dtype=None)\n\narange returns evenly spaced values within a given interval. The values are generated within the half-open interval '[start, stop)' If the function is used with integers, it is nearly equivalent to the Python built-in function range, but arange returns an ndarray rather than a list iterator as range does. If the 'start' parameter is not given, it will be set to 0. The end of the interval is determined by the parameter 'stop'. Usually, the interval will not include this value, except in some cases where 'step' is not an integer and floating point round-off affects the length of output ndarray. The spacing between two adjacent values of the output array is set with the optional parameter 'step'. The default value for 'step' is 1. If the parameter 'step' is given, the 'start' parameter cannot be optional, i.e. it has to be given as well. The type of the output array can be specified with the parameter 'dtype'. If it is not given, the type will be automatically inferred from the other input arguments.\n\nThe syntax of linspace:\n\nlinspace(start, stop, num=50, endpoint=True, retstep=False)\n\nlinspace returns an ndarray, consisting of 'num' equally spaced samples in the closed interval [start, stop] or the half-open interval [start, stop). If a closed or a half-open interval will be returned, depends on whether 'endpoint' is True or False. The parameter 'start' defines the start value of the sequence which will be created. 'stop' will the end value of the sequence, unless 'endpoint' is set to False. In the latter case, the resulting sequence will consist of all but the last of 'num + 1' evenly spaced samples. This means that 'stop' is excluded. Note that the step size changes when 'endpoint' is False. The number of samples to be generated can be set with 'num', which defaults to 50. If the optional parameter 'endpoint' is set to True (the default), 'stop' will be the last sample of the sequence. Otherwise, it is not included.\n\n\n\n\"\"\"\n", "meta": {"hexsha": "e9182049826da6ca7724e071442bd90b5e83e057", "size": 2540, "ext": "py", "lang": "Python", "max_stars_repo_path": "2.arange_&linespace.py", "max_stars_repo_name": "Mansihpatel/numpy-practise", "max_stars_repo_head_hexsha": "e6edd8e21b7b5da9274bbaea17fdafbe87b1d17d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2.arange_&linespace.py", "max_issues_repo_name": "Mansihpatel/numpy-practise", "max_issues_repo_head_hexsha": "e6edd8e21b7b5da9274bbaea17fdafbe87b1d17d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.arange_&linespace.py", "max_forks_repo_name": "Mansihpatel/numpy-practise", "max_forks_repo_head_hexsha": "e6edd8e21b7b5da9274bbaea17fdafbe87b1d17d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.1282051282, "max_line_length": 1012, "alphanum_fraction": 0.7496062992, "include": true, "reason": "import numpy", "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9532750372256349, "lm_q1q2_score": 0.9137500854050156}} {"text": "#T# exponentiation is the operation of multiplying a number by itself several times\n\n#T# the exponentiation ** operator can be used to raise the first number to the power of the second\nnum1 = 2 ** 4 # 16 #| 16 is 2 to the 4th power\nnum1 = 5 ** -1 # 0.2\n\n#T# the pow function is used to raise the first number to the power of the second\nnum1 = pow(2, 4) # 16 #| 16 is 2 to the 4th power\n\n#T# to raise a list or array to the power of another list or array element-wise, the numpy package is used\nimport numpy as np\n\n#T# the power function raises the first array to the power of the second element-wise, it supports array broadcasting\narr1 = np.array([[2, 3, 2, 4], [3, 2, 2, 5]])\narr2 = np.array([6, 4, 5, 2])\narr3 = np.power(arr1, arr2)\n# array([[ 64, 81, 32, 16], [729, 16, 32, 25]])\n\n#T# the exponentiation ** operator can be used to raise the first array to the power of the second element-wise, it supports array broadcasting\narr1 = np.array([[2, 3, 2, 4], [3, 2, 2, 5]])\narr2 = np.array([6, 4, 5, 2])\narr3 = arr1 ** arr2\n# array([[ 64, 81, 32, 16], [729, 16, 32, 25]])", "meta": {"hexsha": "2abede61afc6811b8dbababa037bcb3ac9b3c44d", "size": 1085, "ext": "py", "lang": "Python", "max_stars_repo_path": "Math/A01_Arithmetics_basics/Programs/S03/Exponentiation.py", "max_stars_repo_name": "Polirecyliente/SGConocimiento", "max_stars_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math/A01_Arithmetics_basics/Programs/S03/Exponentiation.py", "max_issues_repo_name": "Polirecyliente/SGConocimiento", "max_issues_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/A01_Arithmetics_basics/Programs/S03/Exponentiation.py", "max_forks_repo_name": "Polirecyliente/SGConocimiento", "max_forks_repo_head_hexsha": "560b08984236d7a10f50c6b5e6fb28844193d81b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1739130435, "max_line_length": 143, "alphanum_fraction": 0.664516129, "include": true, "reason": "import numpy", "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9871787838473909, "lm_q2_score": 0.9252299648234481, "lm_q1q2_score": 0.9133673914535757}} {"text": "from scipy.optimize import newton, bisect, fsolve, root\n\nf = lambda x: 2*x**2 - 5*x + 3\n\n# Newton-Raphson Function\nprint('newton(f, 0) = %f' % newton(f, 0))\nprint('newton(f, 2) = %f' % newton(f, 2), end='\\n\\n')\n\n# Bisection Function\nprint('bisect(f, 0, 1.3) = %f' % bisect(f, 0, 1.3))\nprint('bisect(f, 2, 1.3) = %f' % bisect(f, 2, 1.3), end='\\n\\n')\n\n# FSolve Function\nprint('fsolve (f, 0) =', fsolve(f, 0))\nprint('fsolve (f, 2) =', fsolve(f, 2), end='\\n\\n')\n\nx0 = [-1, 0, 1, 2, 3, 4]\nprint(' x0 =', x0)\nprint('fsolve(f, x0) =', fsolve(f, x0), end='\\n\\n')\n\n# Root Function\nprint('root(f, 2) =', root(f, 2), sep='\\n', end='\\n\\n')\n\nprint('root (f, 0).x =', root(f, 0).x)\nprint('root (f, 2).x =', root(f, 2).x, end='\\n\\n')\n\nprint(' x0 =', x0)\nprint('root(f, x0).x =', root(f, x0).x)\n\n\n\n\n# Default print parameters:\n# print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)\n", "meta": {"hexsha": "7eb870436822e9b84c91549a0036535636d7f3fd", "size": 898, "ext": "py", "lang": "Python", "max_stars_repo_path": "1. Roots of High-Degree Equations/0. Root finding functions of SciPy.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1. Roots of High-Degree Equations/0. Root finding functions of SciPy.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1. Roots of High-Degree Equations/0. Root finding functions of SciPy.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6571428571, "max_line_length": 66, "alphanum_fraction": 0.5389755011, "include": true, "reason": "from scipy", "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877726405082, "lm_q2_score": 0.9407897471835636, "lm_q1q2_score": 0.9132131042166401}} {"text": "'''\nThis problem was asked by Google.\n\nThe area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.\n\nHint: The basic equation of a circle is x2 + y2 = r2.\n'''\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n'''\nwe have a circle of radius 1, enclosed by a 2 × 2 square. The area of the circle is πr**2=π(1)**2 = π, \nthe area of the square is 4. If we divide the area of the circle, by the area of the square we get π/4.\n\nWe then generate a large number of uniformly distributed random points and plot them on the graph. \nThese points can be in any position within the square i.e. between (-1,-1) and (1,1). \nIf they fall within the circle(x2 + y2 = r2), \nthey are coloured red, otherwise they are coloured green. \nWe keep track of the total number of points, and the number of points that are inside the circle. \nIf we divide the number of points within the circle, N_inner by the total number of points, N_total, \nwe should get a value that is an approximation of the ratio of the areas we calculated above, π/4.\n\nIn other words,\n\nπ/4 ≈ Ninner/Ntotal\nπ ≈4* (Ninner/Ntotal)\n\nWhen we only have a small number of points, \nthe estimation is not very accurate, but when we have hundreds of thousands of points, \nwe get much closer to the actual value - to within around 2 decimal places of accuracy.\n'''\n\n\ndef MC_pi():\n # pi = 3.141592\n n = 1000000 # number of data points\n #data = np.random.rand(n, 2) # generate uniform random x,y points b/w [0,1)\n data = np.random.uniform(low=-1, high=1, size=(n,2))\n inside = data[ np.sqrt(data[:,0]**2 + data[:,1]**2) < 1]\n pi = 4* len(inside)/len(data)\n plt.figure(figsize=(8,8))\n plt.scatter(data[:,0], data[:,1], s=.5, c='red')\n plt.scatter(inside[:, 0], inside[:, 1], s=.5, c='green')\n plt.show()\n return pi\n\n\nif __name__ == '__main__':\n print(MC_pi())", "meta": {"hexsha": "57cb69ec941241c6c28c5ab17e33bb4dde54b9e7", "size": 1873, "ext": "py", "lang": "Python", "max_stars_repo_path": "DailyCodingProblem/14_Google_MonteCarlo_pi_Estimate.py", "max_stars_repo_name": "RafayAK/CodingPrep", "max_stars_repo_head_hexsha": "718eccb439db0f6e727806964766a40e8234c8a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-09-07T17:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:59:46.000Z", "max_issues_repo_path": "DailyCodingProblem/14_Google_MonteCarlo_pi_Estimate.py", "max_issues_repo_name": "RafayAK/CodingPrep", "max_issues_repo_head_hexsha": "718eccb439db0f6e727806964766a40e8234c8a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DailyCodingProblem/14_Google_MonteCarlo_pi_Estimate.py", "max_forks_repo_name": "RafayAK/CodingPrep", "max_forks_repo_head_hexsha": "718eccb439db0f6e727806964766a40e8234c8a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-07T17:31:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-28T16:10:52.000Z", "avg_line_length": 36.7254901961, "max_line_length": 103, "alphanum_fraction": 0.6876668446, "include": true, "reason": "import numpy", "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737826, "lm_q2_score": 0.9390248148690405, "lm_q1q2_score": 0.9131215495822367}} {"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n# ## Approximation\n\ndef f(x):\n return np.sin(x) + 0.5 * x\n\nx = np.linspace(-2 * np.pi, 2 * np.pi, 50)\n\nplt.plot(x, f(x), 'b')\nplt.grid(True)\nplt.xlabel('x')\nplt.ylabel('f(x)')\n\n# ### Regression\n\n# #### Linear regresion\n\nreg = np.polyfit(x, f(x), deg=1)\nry = np.polyval(reg, x)\n\nplt.plot(x, f(x), 'b', label='f(x)')\nplt.plot(x, ry, 'r.', label='regression')\nplt.legend(loc=0)\nplt.grid(True)\nplt.xlabel('x')\nplt.ylabel('f(x)')\n\n# ## Higher order polynomials\nreg = np.polyfit(x, f(x), deg=5)\nry = np.polyval(reg, x)\n\nplt.plot(x, f(x), 'b', label='f(x)')\nplt.plot(x, ry, 'r.', label='regression')\nplt.legend(loc=0)\nplt.grid(True)\nplt.xlabel('x')\nplt.ylabel('f(x)')\n\nnp.allclose(f(x), ry) # check if are numerically identical (change deg to 7 to get true)\n\nnp.sum((f(x) - ry) ** 2) / len(x)\n\n# ### Constrained Optimization\n\n# function to be minimized\n# EXAMPLE\n# An investor wants to maximize the expected utility by investing in two risky securities\n# a,b that cost 10 today. After one year, on state u they get payoffs (15,5) and on state\n# d they get payoffs (5,12). The budget of the investor is 100 and has an utility function\n# utility(wealth) = sqrt(wealth)\n\ndef Eu(p):\n a, b = p\n return -(0.5 * np.sqrt(a * 15 + b * 5) + 0.5 * np.sqrt(a * 5 + b * 12))\n\n# constraints\ncons = ({'type': 'ineq', 'fun': lambda p: 100 - p[0] * 10 - p[1] * 10})\n # budget constraint\nbnds = ((0, 1000), (0, 1000)) # uppper bounds large enough\n\n\nresult = spo.minimize(Eu, [5, 5], method='SLSQP',bounds=bnds, constraints=cons)\n\nresult['x']@[10,10] # Check if the investor depletes budget\n-result['fun']\n\n# ## Integration\nimport scipy.integrate as sci\n\ndef f(x):\n return np.sin(x) + 0.5 * x\n\na = 0.5 # left integral limit\nb = 9.5 # right integral limit\nx = np.linspace(0, 10)\ny = f(x)\n\nsci.fixed_quad(f, a, b)[0] # Fixed Gaussian quadrature rule\n\nsci.quad(f, a, b)[0] # Adaptive quadrature\n\nsci.romberg(f, a, b)\n\n\n# ### Integration by Simulation (compare with values above)\n\n# Monte Carlo integration: simulate a path, sum the function values, average\nfor i in range(1, 20):\n np.random.seed(1000)\n x = np.random.random(i * 10) * (b - a) + a\n print(np.sum(f(x)) / len(x) * (b - a))\n", "meta": {"hexsha": "6634ecb0dcf14e863e5548db6ef77a62d0f83900", "size": 2234, "ext": "py", "lang": "Python", "max_stars_repo_path": "09 Math tools.py", "max_stars_repo_name": "jpmaldonado/python4finance", "max_stars_repo_head_hexsha": "d21f772e79f9b1b10ecc71c69d088c69c3bea1fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "09 Math tools.py", "max_issues_repo_name": "jpmaldonado/python4finance", "max_issues_repo_head_hexsha": "d21f772e79f9b1b10ecc71c69d088c69c3bea1fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "09 Math tools.py", "max_forks_repo_name": "jpmaldonado/python4finance", "max_forks_repo_head_hexsha": "d21f772e79f9b1b10ecc71c69d088c69c3bea1fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7659574468, "max_line_length": 90, "alphanum_fraction": 0.633393017, "include": true, "reason": "import numpy,import scipy", "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899577232538, "lm_q2_score": 0.9449947084146744, "lm_q1q2_score": 0.9127699893447195}} {"text": "#py_numpy.py\n\n\"\"\"This script contains code to demonstrate basic operations\n using numpy arrays\n\"\"\" \n\n\n#import the library:\nimport numpy as np\n\n#create an array simply by populating it\na=np.zeros((3,4)); b=np.ones(3)\narr = np.array([1, 2, 3]) \nprint(arr)\nprint(type(arr))\nprint()\n\n#the array knows a lot about itself and can be sliced like a list\nprint(arr.shape)\nprint(arr[-1])\nprint(arr[1:3])\nprint()\n\n#you can create a 2d array like a list of lists\narr2d = np.array([[1,2,3],[4,5,6], [7, 8, 9]]) \nprint(arr2d)\nprint (arr2d.shape)\nprint(arr2d[2, 1])\nprint()\n\n#now, you can address elements with 2d slicking\nnew2d=arr2d[1:, 1:]\nprint(new2d)\nprint()\n\n#you can address one 'dimension' at a time\nnew1d_row=arr2d[1,]\nprint(new1d_row)\nnew1d_col=arr2d[:,1]\nprint(new1d_col)\nprint()\n\n#scalar options are easy\ndouble=arr2d*2\nprint(double)\nsquare=arr2d**2\nprint(square)\nprint()\n\n#you can make \"deep copies\" just like lists\ncopy_arr2d=arr2d[:]\ncopy_arr2d[1,]=copy_arr2d[1,]*2\nprint(copy_arr2d)\nprint()\n\n#stats\nprint(\"max\", arr2d.max())\nprint(\"mean\", arr2d.mean())\nprint(\"min\", arr2d.min())\nprint(\"sd\", arr2d.std())\nprint(\"sum\", arr2d.sum())\nprint(\"transpose\\n\", arr2d.T)\nprint()\n\n#row, column masks for a diagional\nrow_mask=np.array([0,1,2])\ncol_mask=np.array([0,1,2])\ndiagonal=arr2d[row_mask, col_mask]\nprint(diagonal)\n\n#or, just use the built-in\nprint(arr2d.diagonal())\nprint()\n\n#it's possible to create a boolean mask\nboolean_ix=arr2d % 2 == 0 #filter evens\nprint(boolean_ix)\n\nevens=arr2d*boolean_ix\nprint(evens)\nprint()\n\n#extract evens\njust_evens=arr2d[boolean_ix]\nprint(just_evens)\nprint()\n\n\n#matrix ops\na_arr = np.array([[1,2],[3,4]])\nb_arr = np.array([[5,6],[7,8]])\nc_arr = np.array([9,10])\nd_arr = np.array([11, 12])\n\n# Scalar Products\nprint(\"scalar product of:\\n\", c_arr, \"\\nand\\n\", d_arr, '\\n')\nprint (c_arr.dot(d_arr))\nprint (np.dot(c_arr, d_arr))\nprint()\n\n# Matrix Products \nprint(\"matrix product of:\\n\", a_arr, \"\\nand\\n\", c_arr, '\\n')\nprint (a_arr.dot(c_arr))\nprint (np.dot(a_arr, c_arr))\nprint()\n\nprint(\"matrix product of:\\n\", a_arr, \"\\nand\\n\", b_arr, '\\n')\nprint (a_arr.dot(b_arr))\nprint (np.dot(a_arr, b_arr))\nprint()\n\n", "meta": {"hexsha": "8ca8986c2416c60cc4563fba3eb307ba5f4f1870", "size": 2132, "ext": "py", "lang": "Python", "max_stars_repo_path": "dkr-py310/docker-student-portal-310/course_files/data_sci_mini/py_numpy.py", "max_stars_repo_name": "pbarton666/virtual_classroom", "max_stars_repo_head_hexsha": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dkr-py310/docker-student-portal-310/course_files/data_sci_mini/py_numpy.py", "max_issues_repo_name": "pbarton666/virtual_classroom", "max_issues_repo_head_hexsha": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dkr-py310/docker-student-portal-310/course_files/data_sci_mini/py_numpy.py", "max_forks_repo_name": "pbarton666/virtual_classroom", "max_forks_repo_head_hexsha": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0357142857, "max_line_length": 65, "alphanum_fraction": 0.6894934334, "include": true, "reason": "import numpy", "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.948154530786456, "lm_q1q2_score": 0.9127628724155811}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef sample_expt():\n\tmu = 0.0\n\tsigma_2 = 1.0\n\tN = 5\n\n\tsamples = np.random.normal(mu, sigma_2, N)\n\n\t# print samples\n\n\tmu_MLE = np.sum(samples)/N\n\n\tsigma_2_MLE = np.sum(np.power((samples - mu_MLE*np.ones_like(samples)),2))/N\n\n\t# print 'my_MLE = %f, sigma_2_MLE = %f' % (mu_MLE, sigma_2_MLE)\n\treturn mu_MLE, sigma_2_MLE\n\nmu_MLE, sigma_2_MLE = sample_expt()\nprint 'MLE estimate of mean based on 5 samples = %f' % mu_MLE\nprint 'MLE estimate of variance based on 5 samples = %f' % sigma_2_MLE\n# print 'mu_MLE = %f, sigma_2_MLE = %f' % (mu_MLE, sigma_2_MLE)\n\nsigma_2_arr = np.empty([10000,1], dtype=float)\nmu_arr = np.empty([10000,1], dtype=float)\n\nfor i in range(10000):\n\tmu_MLE, sigma_2_MLE = sample_expt()\n\tsigma_2_arr[i,:] = sigma_2_MLE\n\tmu_arr[i,:] = mu_MLE\n\n\nmean_sigma_2_MLE_freq = np.mean(sigma_2_arr)\nvar_sigma_2_MLE_freq = np.mean(np.power((sigma_2_arr - mean_sigma_2_MLE_freq*np.ones_like(sigma_2_arr)),2))\n\nvariance_true = 1.0\nN = 5\n\nbias_of_variance_estimate = abs(mean_sigma_2_MLE_freq - variance_true)\nvar_of_variance_estimate = var_sigma_2_MLE_freq\n# print 'mean_sigma_2_MLE_freq = %f, var_sigma_2_MLE_freq = %f' % (mean_sigma_2_MLE_freq, var_sigma_2_MLE_freq)\n\nprint 'Bias of variance estimate = %f' % bias_of_variance_estimate\nprint 'Variance of variance estimate = %f' % var_of_variance_estimate\n\nbias_of_variance_estimate_th = abs(variance_true/N)\nvar_of_variance_estimate_th = 2*(N-1)*(variance_true**2)/(N**2)\n\nprint 'Theoretical Bias of variance estimate = %f' % bias_of_variance_estimate_th\nprint 'Theoretical Variance of variance estimate = %f' % var_of_variance_estimate_th\n\ndiff_bias_variance = (bias_of_variance_estimate - bias_of_variance_estimate_th)*100/bias_of_variance_estimate_th\ndiff_var_variance = (var_of_variance_estimate - var_of_variance_estimate_th)*100/var_of_variance_estimate_th\n\nprint 'percentage difference between Theoretical and Frequentist result for bias of variance estimate = %f ' % diff_bias_variance\nprint 'percentage difference between Theoretical and Frequentist result for variance of variance estimate = %f' % diff_var_variance\n\nplt.hist(sigma_2_arr,'auto')\nplt.title(\"Histogram of variance values\")\nplt.xlabel(\"variance estimate\")\nplt.ylabel(\"Number of samples\")\nplt.show()\n", "meta": {"hexsha": "abde86b4c6d4e64b445fcb96b008fb6a46116bc4", "size": 2277, "ext": "py", "lang": "Python", "max_stars_repo_path": "HWK-1_20081093/q4.py", "max_stars_repo_name": "vardaan123/IFT6269_Aut17", "max_stars_repo_head_hexsha": "23b3b67bda13e7c4c0ca9e402091e17442ddeec8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HWK-1_20081093/q4.py", "max_issues_repo_name": "vardaan123/IFT6269_Aut17", "max_issues_repo_head_hexsha": "23b3b67bda13e7c4c0ca9e402091e17442ddeec8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HWK-1_20081093/q4.py", "max_forks_repo_name": "vardaan123/IFT6269_Aut17", "max_forks_repo_head_hexsha": "23b3b67bda13e7c4c0ca9e402091e17442ddeec8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.578125, "max_line_length": 131, "alphanum_fraction": 0.7751427317, "include": true, "reason": "import numpy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812345563902, "lm_q2_score": 0.9425067268518421, "lm_q1q2_score": 0.9127058277264893}} {"text": "# Q2: find median for entire sample\n# Q1: find median for first half of the sample\n# Q3: find median for second half of the sample\n\n# Before doing any calculation of Quartiles we need to order the sequence from lowest to highest\n\n\"\"\"\n\nhttps://towardsdatascience.com/what-are-quartiles-c3e117114cf1\n\nQuartiles are position indicators that divide a sequence of numbers into 4 equal parts.\n\nQuartiles analysis is part of descriptive statistics and consequently, helps us better understand\nthe data at hand. With these, specifically, we will understand what is called central tendency or :\n\n“A measure of central tendency is a single value that attempts to describe a set of data by identifying\nthe central position within that set of data”\n\n\"\"\"\n\nimport numpy as np\n\nfrom day0.p01mean_median_mode import median\n\n\ndef quartiles(sample: list) -> list:\n sample.sort()\n size = len(sample)\n mid_index = size // 2\n if size % 2:\n q3 = median(sample[mid_index + 1:])\n else:\n q3 = median(sample[mid_index:])\n return [median(sample[:mid_index]), median(sample), q3]\n\n\nif __name__ == '__main__':\n data = [4, 17, 7, 14, 18, 12, 3, 16, 10, 4, 4, 12]\n result = quartiles(data)\n print(result)\n\n # using numpy\n print('%d' % np.quantile(np.array(data), 0.25))\n print('%d' % np.quantile(np.array(data), 0.5))\n print('%d' % np.quantile(np.array(data), 0.75, interpolation='midpoint'))\n", "meta": {"hexsha": "d88767e011ebf8401125660ba132a4ea095399cc", "size": 1415, "ext": "py", "lang": "Python", "max_stars_repo_path": "day1/p01quartiles.py", "max_stars_repo_name": "chaithrakc/hackerrank-10-days-of-statistics", "max_stars_repo_head_hexsha": "f558ba74a62caea9eaea1889bfd4867fc7b53220", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day1/p01quartiles.py", "max_issues_repo_name": "chaithrakc/hackerrank-10-days-of-statistics", "max_issues_repo_head_hexsha": "f558ba74a62caea9eaea1889bfd4867fc7b53220", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day1/p01quartiles.py", "max_forks_repo_name": "chaithrakc/hackerrank-10-days-of-statistics", "max_forks_repo_head_hexsha": "f558ba74a62caea9eaea1889bfd4867fc7b53220", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7608695652, "max_line_length": 103, "alphanum_fraction": 0.703180212, "include": true, "reason": "import numpy", "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133554, "lm_q2_score": 0.9473810490664701, "lm_q1q2_score": 0.9125463517221906}} {"text": "\"\"\"\r\n\r\nLinear Regression Finder : Given a csv file of the following format calculates the linear regression for the given data.\r\n\r\n Data format:\r\n\r\n x y\r\n \r\n 1\t 2\r\n 2\t 3\r\n 3\t 4\r\n 4\t 5\r\n 5\t 6\r\n 6\t 7\r\n 7\t 8\r\n 8\t 9\r\n 9\t 10\r\n 10\t 11\r\n\r\n Formula :\r\n \r\n y = a + (b * x)\r\n\r\n b = r * (sy / sx)\r\n\r\n a = y1 - (b * x1)\r\n\r\n r = sigma( (x - x1) * (y - y1) ) / sqrt( sigma( (x - x1)**0.5) * sigma( (y - y1)**0.5) )\r\n\r\n\"\"\"\r\nfrom sys import stdin, stdout\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.lines as lines\r\nimport time\r\nimport csv\r\n\r\n\r\ndef load_csv():\r\n\r\n # Getting the name of the csv file to be loaded\r\n\r\n file_name = input(\"enter the name of the csv file : \")\r\n\r\n x = []\r\n\r\n y = []\r\n\r\n # Loading csv file\r\n\r\n try:\r\n\r\n with open(file_name+\".csv\") as csvfile:\r\n\r\n reader = csv.DictReader(csvfile)\r\n\r\n for row in reader:\r\n\r\n x.append(float(row['x']))\r\n\r\n y.append(float(row['y']))\r\n\r\n return x, y, file_name\r\n\r\n except:\r\n\r\n print(\"\\nThe entered csv file dosent exixt.\\n\\nPlease check the name and try again.\\n\")\r\n\r\ndef show_data(x, y):\r\n\r\n # Displaying the content of the csv file\r\n\r\n for i in range(len(x)):\r\n\r\n print(str(x[i])+\"\\t\"+str(y[i]))\r\n\r\ndef linear_reg(x, y):\r\n\r\n # Finding means of x and y as x1 and y1\r\n\r\n x1 = sum(x)/len(x)\r\n\r\n y1 = sum(y)/len(y)\r\n\r\n # Finding the numerator part to calculate r\r\n\r\n x = [i-x1 for i in x]\r\n\r\n y = [i-y1 for i in y]\r\n\r\n z = [x[i]*y[i] for i in range(len(x))]\r\n\r\n # Finding the denominator part to calculate r\r\n\r\n x = [i*i for i in x]\r\n\r\n y = [i*i for i in y]\r\n\r\n # Calculation of r, sy and sx\r\n\r\n r = sum(z)/((sum(x)*sum(y))**0.5)\r\n\r\n sy = (sum(y)/(len(y)-1))**0.5\r\n\r\n sx = (sum(x)/(len(x)-1))**0.5\r\n\r\n # Calculating a and b\r\n\r\n b = r * (sy / sx)\r\n\r\n a = y1 - (b * x1)\r\n\r\n # Finding and displaying y\r\n\r\n val = str(a)+\" + ( \"+str(b)+\" * x )\"\r\n\r\n return val, a, b\r\n\r\ndef scatter_plot(x, y, a, b):\r\n\r\n # Ploting the scatter plot\r\n\r\n area = 100\r\n\r\n colors = np.random.rand(len(x))\r\n\r\n fig, ax = plt.subplots()\r\n\r\n data = plt.scatter(x, y, s=area, c=colors, alpha=1)\r\n\r\n # Finding ends of the regression line\r\n \r\n start = [min(x), max(x)]\r\n\r\n end = [(b * min(x)) + a, (b * max(x)) + a]\r\n\r\n # Plotting the regression line\r\n\r\n reg_line = lines.Line2D(start, end, lw=2, color='black', axes=ax)\r\n\r\n ax.add_line(reg_line)\r\n\r\n # Displaying the plots\r\n\r\n ax.grid(True)\r\n\r\n plt.axis('equal')\r\n\r\n plt.tight_layout()\r\n\r\n plt.show()\r\n\r\ndef predict(a, b):\r\n\r\n test_x = float(input(\"Enter the value of x for which y is to be predicted : \"))\r\n\r\n test_y = a + (b * test_x)\r\n\r\n print(\"\\nFor x = \"+str(test_x)+\" y = \"+str(test_y)+\"\\n\")\r\n\r\n return test_x, test_y\r\n\r\ndef update_csv(test_x, test_y, file_name):\r\n\r\n # Updating the CSV file with the predicted value\r\n\r\n fields = [test_x, test_y]\r\n\r\n with open(file_name+\".csv\", 'a') as f:\r\n\r\n writer = csv.writer(f)\r\n\r\n writer.writerow(fields)\r\n\r\ndef clear_data_set():\r\n\r\n # Clearing the data set by resetting the values\r\n\r\n x = []\r\n\r\n y = []\r\n\r\n a = 0\r\n\r\n b = 0\r\n\r\n val = \"\"\r\n\r\n return x, y, a, b, val\r\n \r\ndef main():\r\n\r\n try:\r\n\r\n op = 0\r\n \r\n while op != 8:\r\n\r\n op = int(input(\"Choose your option :\\n\\n1. Load csv\\n2. Show data\\n3. Find Linear regression equ\\n4. Show scatter plot\\n5. Predict\\n6. Update CSV\\n7. Clear Data Set\\n8. Exit\\n\\n\"))\r\n\r\n print()\r\n \r\n if op == 1:\r\n\r\n x, y, file_name = load_csv()\r\n\r\n x = np.array(x)\r\n\r\n y = np.array(y)\r\n\r\n print()\r\n\r\n elif op == 2:\r\n\r\n show_data(x, y)\r\n\r\n print()\r\n\r\n elif op == 3:\r\n\r\n val, a, b = linear_reg(x, y)\r\n\r\n print(\"y = \"+val)\r\n\r\n print()\r\n\r\n elif op == 4:\r\n\r\n scatter_plot(x, y, a, b)\r\n\r\n elif op == 5:\r\n\r\n test_x, test_y = predict(a, b)\r\n\r\n elif op == 6:\r\n\r\n update_csv(test_x, test_y, file_name)\r\n\r\n elif op == 7:\r\n\r\n x, y, a, b, val = clear_data_set()\r\n\r\n elif op == 8:\r\n\r\n exit()\r\n\r\n else:\r\n\r\n print(\"\\ninvalid input\\n\\nplease select a valid input\\n\")\r\n\r\n except:\r\n\r\n print(\"Something went wrong try again.\")\r\n\r\nif __name__ == \"__main__\":\r\n\r\n main()\r\n", "meta": {"hexsha": "23b71d43804ff74a4cc9bf488233a75e29a7abe5", "size": 4640, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear_regression_calculator.py", "max_stars_repo_name": "vishnu2981997/Linear_Regression_Finder", "max_stars_repo_head_hexsha": "1904eb9446adb4fe992903a65e09b34e7b8ac44b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-18T17:55:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-18T17:55:09.000Z", "max_issues_repo_path": "linear_regression_calculator.py", "max_issues_repo_name": "vishnu2981997/Linear_Regression_Finder", "max_issues_repo_head_hexsha": "1904eb9446adb4fe992903a65e09b34e7b8ac44b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression_calculator.py", "max_forks_repo_name": "vishnu2981997/Linear_Regression_Finder", "max_forks_repo_head_hexsha": "1904eb9446adb4fe992903a65e09b34e7b8ac44b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.984496124, "max_line_length": 193, "alphanum_fraction": 0.4726293103, "include": true, "reason": "import numpy", "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347890464284, "lm_q2_score": 0.9362850124150441, "lm_q1q2_score": 0.9123486885599862}} {"text": "import numpy as np\nfrom scipy.linalg import solve\nfrom helpers import Vehicle, show_trajectory\n \nA = np.random.random((3, 3))\nb = np.random.random(3)\n\nx = solve(A, b)\n\n\ndef JMT(start, end, T):\n\n\tsi = start[0]\n\tsi_dot = start[1]\n\tsi_double_dot = start[2]\n\n\tsf = end[0]\n\tsf_dot = end[1]\n\tsf_double_dot = end[2]\n\n\n\tA = [\n\t\t [T**3\t, T**4\t , T**5\t ],\n\t\t [3*T**2, 4*T**3 , 5*T**4],\n\t\t [6*T\t, 12*T**2, 20*T**3]\n\t\t]\n\n\tb = [sf - (si + si_dot*T + 0.5 * si_double_dot * T**2 ), \n\t\t sf_dot - (si_dot + si_double_dot*T), \n\t\t sf_double_dot - si_double_dot]\n\n\tx = solve(A,b)\n\n\tr = np.array([si, si_dot, 0.5*si_double_dot, x[0], x[1], x[2]])\n\n\treturn r\n\t#return [si, si_dot, 0.5*si_double_dot, x[0], x[1], x[2]]\n\n\n\ndef close_enough(poly, target_poly, eps=0.01):\n\tif len(poly) != len(target_poly):\n\t\tprint(\"your solution didn't have the correct number of terms\")\n\t\treturn False\n\t\n\tfor i in range(len(poly)):\n\t\tdiff = poly[i]-target_poly[i]\n\t\tif(abs(diff) > eps):\n\t\t\tprint(\"at least one of your terms differed from target by more than \", eps )\n\t\t\treturn False\n\t\n\treturn True\n\t\n\nanswers = [[0.0, 10.0, 0.0, 0.0, 0.0, 0.0],[0.0,10.0,0.0,0.0,-0.625,0.3125],[5.0,10.0,1.0,-3.0,0.64,-0.0432]];\n\n# create test cases\n\n\ntc1 = [[0,10,0], [10,10,0], [1]]\n\ntc2 = [[0,10,0],[20,15,20], [2]]\n\ntc3 = [[5,10,2],[-30,-20,-4], [5]]\n\ntc = [tc1,tc2,tc3]\n\ni = 0;\ntotal_correct = True\nfor test in tc:\n\tjmt = JMT(test[0], test[1], test[2][0])\n\tcorrect = close_enough(jmt, answers[i])\n\ttotal_correct &= correct\n\ti += 1\n\n\n\nif total_correct:\n\tprint(\"Nice work!\")\nelse:\n\tprint(\"Try again!\")\n\njmt = JMT(tc1[0], tc1[1], tc1[2][0])\nshow_trajectory(jmt[0], jmt[1], jmt[2])\n\t\n", "meta": {"hexsha": "da37769975ac5b61bf07fa2c05f69558b953d176", "size": 1629, "ext": "py", "lang": "Python", "max_stars_repo_path": "trajectory/src/main.py", "max_stars_repo_name": "jjaviergalvez/CarND-Term3-Quizes", "max_stars_repo_head_hexsha": "fc7b4932b3836b784cf88387a908054f10ee6648", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trajectory/src/main.py", "max_issues_repo_name": "jjaviergalvez/CarND-Term3-Quizes", "max_issues_repo_head_hexsha": "fc7b4932b3836b784cf88387a908054f10ee6648", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trajectory/src/main.py", "max_forks_repo_name": "jjaviergalvez/CarND-Term3-Quizes", "max_forks_repo_head_hexsha": "fc7b4932b3836b784cf88387a908054f10ee6648", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9418604651, "max_line_length": 110, "alphanum_fraction": 0.5930018416, "include": true, "reason": "import numpy,from scipy", "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105321470077, "lm_q2_score": 0.9343951643678382, "lm_q1q2_score": 0.9122598401595549}} {"text": "\"\"\"Bures distance metric.\"\"\"\nimport numpy as np\n\nfrom toqito.state_metrics import fidelity\n\n\ndef bures_distance(rho_1: np.ndarray, rho_2: np.ndarray, decimals: int = 10) -> float:\n r\"\"\"\n Compute the Bures distance of two density matrices [WikBures]_.\n\n Calculate the Bures distance between two density matrices :code:`rho_1` and :code:`rho_2`\n defined by:\n\n .. math::\n \\sqrt{2 (1 - F(\\rho_1, \\rho_2))},\n\n where :math:`F(\\cdot)` denotes the fidelity between :math:`\\rho_1` and :math:`\\rho_2`. The\n return is a value between :math:`0` and :math:`\\sqrt{2}`,with :math:`0` corresponding to\n matrices: :code:`rho_1 = rho_2` and :math:`\\sqrt{2}` corresponding to the case: :code:`rho_1`\n and :code:`rho_2` with orthogonal support.\n\n Examples\n ==========\n\n Consider the following Bell state\n\n .. math::\n u = \\frac{1}{\\sqrt{2}} \\left( |00 \\rangle + |11 \\rangle \\right) \\in \\mathcal{X}.\n\n The corresponding density matrix of :math:`u` may be calculated by:\n\n .. math::\n \\rho = u u^* = \\frac{1}{2} \\begin{pmatrix}\n 1 & 0 & 0 & 1 \\\\\n 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 \\\\\n 1 & 0 & 0 & 1\n \\end{pmatrix} \\in \\text{D}(\\mathcal{X}).\n\n In the event where we calculate the Bures distance between states that are identical, we\n should obtain the value of :math:`0`. This can be observed in :code:`toqito` as follows.\n\n >>> from toqito.state_metrics import bures_distance\n >>> import numpy as np\n >>> rho = 1 / 2 * np.array(\n >>> [[1, 0, 0, 1],\n >>> [0, 0, 0, 0],\n >>> [0, 0, 0, 0],\n >>> [1, 0, 0, 1]]\n >>> )\n >>> sigma = rho\n >>> bures_distance(rho, sigma)\n 0\n\n References\n ==========\n .. [WikBures] Wikipedia: Bures metric\n https://en.wikipedia.org/wiki/Bures_metric\n\n :param rho_1: Density operator.\n :param rho_2: Density operator.\n :param decimals: Number of decimal places to round to (default 10).\n :return: The Bures distance between :code:`rho_1` and :code:`rho_2`.\n \"\"\"\n # Perform some error checking.\n if not np.all(rho_1.shape == rho_2.shape):\n raise ValueError(\"InvalidDim: `rho_1` and `rho_2` must be matrices of the same size.\")\n # Round fidelity to only 10 decimals to avoid error when :code:`rho_1 = rho_2`.\n return np.sqrt(2.0 * (1.0 - np.round(fidelity(rho_1, rho_2), decimals)))\n", "meta": {"hexsha": "ca526a09b35573f4beab4c2bc01f1652f76280f4", "size": 2469, "ext": "py", "lang": "Python", "max_stars_repo_path": "toqito/state_metrics/bures_distance.py", "max_stars_repo_name": "paniash/toqito", "max_stars_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76, "max_stars_repo_stars_event_min_datetime": "2020-01-28T17:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T18:02:15.000Z", "max_issues_repo_path": "toqito/state_metrics/bures_distance.py", "max_issues_repo_name": "paniash/toqito", "max_issues_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 82, "max_issues_repo_issues_event_min_datetime": "2020-05-31T20:09:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:13:59.000Z", "max_forks_repo_path": "toqito/state_metrics/bures_distance.py", "max_forks_repo_name": "paniash/toqito", "max_forks_repo_head_hexsha": "ab67c2a3fca77b3827be11d1e79531042ea62b82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2020-04-02T16:07:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T13:39:22.000Z", "avg_line_length": 35.2714285714, "max_line_length": 97, "alphanum_fraction": 0.5775617659, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703925, "lm_q2_score": 0.9481545349983542, "lm_q1q2_score": 0.9122266588473995}} {"text": "import numpy as np\nfrom scipy import stats\n\n# In[]:\n# Defining 2 random distributions with sample size 10\n# Gaussian distributed data with mean = 2 and var = 1\nNx = 10\nx = np.random.randn(Nx) + 2\n# Gaussian distributed data with with mean = 0 and var = 1\nNy = 10\ny = np.random.randn(Ny)\n\n# In[]:\n\n# Calculate the std dev now\n# ddof : int, optional\n# “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof,\n# where N represents the number of elements. By default ddof is zero.\nvar_x = x.var(ddof=1)\nvar_y = y.var(ddof=1)\n\n# In[]:\n# Calculate the t-statistics\nt = (x.mean() - y.mean()) / (np.sqrt( (var_x/Nx) + (var_y/Ny) ))\n\n# In[]:\n# Compare with the critical t-value\n\n# Degrees of freedom\ndf = Nx + Ny - 2\n# p-value after comparison with the t\np = 1 - stats.t.cdf(t,df=df)\n\n# In[]:\nprint(\"t = \" + str(t))\nprint(\"p = \" + str(2*p))\n# You can see that after comparing the t statistic with the critical t value (computed internally)\n# we get a good p value of 0.0005 and thus we reject the null hypothesis and thus it proves that\n# the mean of the two distributions are different and statistically significant.\n\n# Cross Checking with the internal scipy function, this is a 2tailed p value\nt2, p2 = stats.ttest_ind(x, y)\nprint(\"t = \" + str(t2))\nprint(\"p = \" + str(p2))\n", "meta": {"hexsha": "6bf71c1a179287b1d9e818ce63bb1a0cbdd7e313", "size": 1286, "ext": "py", "lang": "Python", "max_stars_repo_path": "Misc/t_test.py", "max_stars_repo_name": "shaktikshri/adaptiveSystems", "max_stars_repo_head_hexsha": "eeaec975aca4a303344fe8b26289e254049e2ae2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-02-27T02:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T13:24:00.000Z", "max_issues_repo_path": "Misc/t_test.py", "max_issues_repo_name": "shaktikshri/adaptiveSystems", "max_issues_repo_head_hexsha": "eeaec975aca4a303344fe8b26289e254049e2ae2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-10-25T21:02:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:11:15.000Z", "max_forks_repo_path": "Misc/t_test.py", "max_forks_repo_name": "shaktikshri/adaptiveSystems", "max_forks_repo_head_hexsha": "eeaec975aca4a303344fe8b26289e254049e2ae2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-06T09:44:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:39:20.000Z", "avg_line_length": 28.5777777778, "max_line_length": 98, "alphanum_fraction": 0.6858475894, "include": true, "reason": "import numpy,from scipy", "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211597623863, "lm_q2_score": 0.9353465057864692, "lm_q1q2_score": 0.9117955655504614}} {"text": "#1. Write a NumPy program to add, subtract, multiply, divide arguments element-wise.\nimport numpy as np\nprint(\"Add:\")\nprint(np.add(1.0, 4.0))\nprint(\"Subtract:\")\nprint(np.subtract(1.0, 4.0))\nprint(\"Multiply:\")\nprint(np.multiply(1.0, 4.0))\nprint(\"Divide:\")\nprint(np.divide(1.0, 4.0))\n#2. Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.\nimport numpy as np\nl1 = np.log(1e-50)\nl2 = np.log(2.5e-50)\nprint(\"Logarithm of the sum of exponentiations:\")\nprint(np.logaddexp(l1, l2))\nprint(\"Logarithm of the sum of exponentiations of the inputs in base-2:\")\nprint(np.logaddexp2(l1, l2))\n#3. Write a NumPy program to get true division of the element-wise array inputs.\nimport numpy as np\nx = np.arange(10)\nprint(\"Original array:\")\nprint(x)\nprint(\"Division of the array inputs, element-wise:\")\nprint(np.true_divide(x, 3))\n#4. Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.\nimport numpy as np\nx = [1., 2., 3., 4.]\nprint(\"Original array:\")\nprint(x)\nprint(\"Largest integer smaller or equal to the division of the inputs:\")\nprint(np.floor_divide(x, 1.5))\n#5. Write a NumPy program to get the powers of an array values element-wise.\nimport numpy as np\nx = np.arange(7)\nprint(\"Original array\")\nprint(x)\nprint(\"First array elements raised to powers from second array, element-wise:\")\nprint(np.power(x, 3))\n#6. Write a NumPy program to get the element-wise remainder of an array of division.\nimport numpy as np\nx = np.arange(7)\nprint(\"Original array:\")\nprint(x)\nprint(\"Element-wise remainder of division:\")\nprint(np.remainder(x, 5))\n#7. Write a NumPy program to calculate the absolute value element-wise.\nimport numpy as np\nx = np.array([-10.2, 122.2, .20])\nprint(\"Original array:\")\nprint(x)\nprint(\"Element-wise absolute value:\")\nprint(np.absolute(x))\n#8. Write a NumPy program to round array elements to the given number of decimals.\nimport numpy as np\nx = np.round([1.45, 1.50, 1.55])\nprint(x)\nx = np.round([0.28, .50, .64], decimals=1)\nprint(x)\nx = np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value\nprint(x)\n#9. Write a NumPy program to round elements of the array to the nearest integer.\nimport numpy as np\nx = np.array([-.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0])\nprint(\"Original array:\")\nprint(x)\nx = np.rint(x)\nprint(\"Round elements of the array to the nearest integer:\")\nprint(x)\n#10. Write a NumPy program to get the floor, ceiling and truncated values of the elements of a numpy array.\nimport numpy as np\nx = np.array([-1.6, -1.5, -0.3, 0.1, 1.4, 1.8, 2.0])\nprint(\"Original array:\")\nprint(x)\nprint(\"Floor values of the above array elements:\")\nprint(np.floor(x))\nprint(\"Ceil values of the above array elements:\")\nprint(np.ceil(x))\nprint(\"Truncated values of the above array elements:\")\nprint(np.trunc(x))\n#11. Write a NumPy program to multiply a 5x3 matrix by a 3x2 matrix and create a real matrix product.\nimport numpy as np\nx = np.random.random((5,3))\nprint(\"First array:\")\nprint(x)\ny = np.random.random((3,2))\nprint(\"Second array:\")\nprint(y)\nz = np.dot(x, y)\nprint(\"Dot product of two arrays:\")\nprint(z)\n#12. Write a NumPy program to multiply a matrix by another matrix of complex numbers and create a new matrix of complex numbers.\nimport numpy as np\nx = np.array([1+2j,3+4j])\nprint(\"First array:\")\nprint(x)\ny = np.array([5+6j,7+8j])\nprint(\"Second array:\")\nprint(y)\nz = np.vdot(x, y)\nprint(\"Product of above two arrays:\")\nprint(z)\n#13. Write a NumPy program to create an inner product of two arrays.\nimport numpy as np\nx = np.arange(24).reshape((2,3,4))\nprint(\"Array x:\")\nprint(x)\nprint(\"Array y:\")\ny = np.arange(4)\nprint(y)\nprint(\"Inner of x and y arrays:\")\nprint(np.inner(x, y))\n#14. Write a NumPy program to generate inner, outer, and cross products of matrices and vectors.\nimport numpy as np\nx = np.array([1, 4, 0], float)\ny = np.array([2, 2, 1], float)\nprint(\"Matrices and vectors.\")\nprint(\"x:\")\nprint(x)\nprint(\"y:\")\nprint(y)\nprint(\"Inner product of x and y:\")\nprint(np.inner(x, y))\nprint(\"Outer product of x and y:\")\nprint(np.outer(x, y))\nprint(\"Cross product of x and y:\")\nprint(np.cross(x, y))\n#15. Write a NumPy program to generate a matrix product of two arrays.\nimport numpy as np\nx = [[1, 0], [1, 1]]\ny = [[3, 1], [2, 2]]\nprint(\"Matrices and vectors.\")\nprint(\"x:\")\nprint(x)\nprint(\"y:\")\nprint(y)\nprint(\"Matrix product of above two arrays:\")\nprint(np.matmul(x, y))\n#16. Write a NumPy program to find the roots of the following polynomials.\nimport numpy as np\nprint(\"Roots of the first polynomial:\")\nprint(np.roots([1, -2, 1]))\nprint(\"Roots of the second polynomial:\")\nprint(np.roots([1, -12, 10, 7, -10]))\n#17. Write a NumPy program to compute the following polynomial values\nimport numpy as np\nprint(\"Polynomial value when x = 2:\")\nprint(np.polyval([1, -2, 1], 2))\nprint(\"Polynomial value when x = 3:\")\nprint(np.polyval([1, -12, 10, 7, -10], 3))\n#19. Write a NumPy program to calculate mean across dimension, in a 2D numpy array.\nimport numpy as np\nx = np.array([[10, 30], [20, 60]])\nprint(\"Original array:\")\nprint(x)\nprint(\"Mean of each column:\")\nprint(x.mean(axis=0))\nprint(\"Mean of each row:\")\nprint(x.mean(axis=1))\n#20. Write a NumPy program to create a random array with 1000 elements and compute the average, variance, standard deviation of the array elements.\nimport numpy as np\nx = np.random.randn(1000)\nprint(\"Average of the array elements:\")\nmean = x.mean()\nprint(mean)\nprint(\"Standard deviation of the array elements:\")\nstd = x.std()\nprint(std)\nprint(\"Variance of the array elements:\")\nvar = x.var()\nprint(var)\n", "meta": {"hexsha": "cde2ad71be08cf8bb81f6da3c6bd454e8f00230b", "size": 5572, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy:Basic Mathematics 1.py", "max_stars_repo_name": "AmalChandru/numpy-recipes", "max_stars_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-14T14:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T03:14:20.000Z", "max_issues_repo_path": "NumPy:Basic Mathematics 1.py", "max_issues_repo_name": "AmalChandru/numpy-recipes", "max_issues_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy:Basic Mathematics 1.py", "max_forks_repo_name": "AmalChandru/numpy-recipes", "max_forks_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3953488372, "max_line_length": 147, "alphanum_fraction": 0.7056712132, "include": true, "reason": "import numpy", "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011975, "lm_q2_score": 0.9372107979795822, "lm_q1q2_score": 0.9117474985967915}} {"text": "import numpy as np\nnp.set_printoptions(linewidth=1000)\n\n\ndef softmax(vector: np.array) -> np.array:\n \"\"\"\n My own implementation of the softmax function\n\n Parameters\n ----------\n vector\n\n Returns\n -------\n\n \"\"\"\n\n # Notice that\n # exp(x_i)/sum_i exp(x_i)\n # = [exp(-m)/exp(-m)]exp(x_i)/sum_i exp(x_i)\n # = exp(x_i - m)/sum_i exp(x_i-m)\n\n # I add some gymnastics to allow this to work on vectors as well as arrays\n if len(vector.shape) == 1:\n vector = vector.reshape(1, -1)\n reshape = True\n else:\n reshape = False\n\n nominator = np.exp(vector - np.max(vector))\n denominator = nominator.sum(axis=1, keepdims=True)\n\n result = nominator / denominator\n\n if reshape:\n result = result.reshape(-1,)\n return result\n\n\ndef sigmoid(x):\n return 1/(1 + np.exp(-x))\n\n\ndef cross_entropy(predictions, targets, epsilon=1e-12):\n \"\"\"\n\n Parameters\n ----------\n predictions: np.array(N, k)\n targets: np.array(N, k)\n epsilon: float\n Correction factor for numerical stability\n\n Returns\n -------\n\n \"\"\"\n predictions = np.clip(predictions, epsilon, 1. - epsilon)\n N = predictions.shape[0]\n result = -np.sum(targets*np.log(predictions+1e-9))/N\n return result\n\n\ndef relu(X):\n # np.maximum keeps the shape of X! np.max returns less dimensional objects\n return np.maximum(X, 0)\n", "meta": {"hexsha": "bbb71bb041220ff5075a827debc50ddcdb2db040", "size": 1387, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/utils/activation.py", "max_stars_repo_name": "MartinBCN/BasicML", "max_stars_repo_head_hexsha": "7ad7bd075c62d883143dd10b54c80287d06a99b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/activation.py", "max_issues_repo_name": "MartinBCN/BasicML", "max_issues_repo_head_hexsha": "7ad7bd075c62d883143dd10b54c80287d06a99b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/activation.py", "max_forks_repo_name": "MartinBCN/BasicML", "max_forks_repo_head_hexsha": "7ad7bd075c62d883143dd10b54c80287d06a99b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7014925373, "max_line_length": 78, "alphanum_fraction": 0.6034607066, "include": true, "reason": "import numpy", "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407160384082, "lm_q2_score": 0.9362850093037731, "lm_q1q2_score": 0.9112306928708318}} {"text": "import numpy as np\n\ndef homography2d(x1, x2):\n \"\"\"\n Direct Linear Transform \n \n Input:\n x1: 3xN set of homogeneous points\n x2: 3xN set of homogeneous points such that x1<->x2\n\n Returns:\n H: the 3x3 homography such that x2 = H*x1\n \"\"\"\n [x1, T1] = normalise2dpts(x1)\n [x2, T2] = normalise2dpts(x2)\n\n Npts = x1.shape[1]\n\n A = np.zeros((3*Npts,9))\n \n O = np.zeros(3);\n\n for i in range(0, Npts):\n X = x1[:,i].T\n x = x2[0,i]\n y = x2[1,i]\n w = x2[2,i]\n A[3*i,:] = np.array([O, -w*X, y*X]).reshape(1, 9)\n A[3*i+1,:] = np.array([w*X, O, -x*X]).reshape(1, 9)\n A[3*i+2,:] = np.array([-y*X, x*X, O]).reshape(1, 9)\n\n [U,D,Vh] = np.linalg.svd(A)\n V = Vh.T\n\n H = V[:,8].reshape(3,3)\n\n H = np.linalg.solve(T2, H)\n H = H.dot(T1)\n\n return H\n \n \ndef normalise2dpts(pts):\n \"\"\"\n Function translates and normalises a set of 2D homogeneous points \n so that their centroid is at the origin and their mean distance from \n the origin is sqrt(2). This process typically improves the\n conditioning of any equations used to solve homographies, fundamental\n matrices etc.\n \n \n Inputs:\n pts: 3xN array of 2D homogeneous coordinates\n \n Returns:\n newpts: 3xN array of transformed 2D homogeneous coordinates. The\n scaling parameter is normalised to 1 unless the point is at\n infinity. \n T: The 3x3 transformation matrix, newpts = T*pts\n \"\"\"\n if pts.shape[0] != 3:\n print(\"Input shoud be 3\")\n\n finiteind = np.nonzero(abs(pts[2,:]) > np.spacing(1));\n \n if len(finiteind) != pts.shape[1]:\n print('Some points are at infinity')\n \n dist = []\n for i in finiteind:\n pts[0,i] = pts[0,i]/pts[2,i]\n pts[1,i] = pts[1,i]/pts[2,i]\n pts[2,i] = 1;\n\n c = np.mean(pts[0:2,i].T, axis=0).T \n\n newp1 = pts[0,i]-c[0]\n newp2 = pts[1,i]-c[1]\n \n \tdist.append(np.sqrt(newp1**2 + newp2**2))\n\n meandist = np.mean(dist[:])\n \n scale = np.sqrt(2)/meandist\n \n T = np.array([[scale, 0, -scale*c[0]], [0, scale, -scale*c[1]], [0, 0, 1]])\n \n newpts = T.dot(pts)\n\n return [newpts, T]\n", "meta": {"hexsha": "dbab2927860a618804985ded757b8e5b3c0d27d3", "size": 2226, "ext": "py", "lang": "Python", "max_stars_repo_path": "ippe/homo2d.py", "max_stars_repo_name": "royxue/ippe_py", "max_stars_repo_head_hexsha": "0dec82d959aa9da339be05722a50c8bc47047a1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-03-23T00:18:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T17:38:29.000Z", "max_issues_repo_path": "ippe/homo2d.py", "max_issues_repo_name": "royxue/ippe_py", "max_issues_repo_head_hexsha": "0dec82d959aa9da339be05722a50c8bc47047a1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-23T02:27:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T10:18:40.000Z", "max_forks_repo_path": "ippe/homo2d.py", "max_forks_repo_name": "royxue/ippe_py", "max_forks_repo_head_hexsha": "0dec82d959aa9da339be05722a50c8bc47047a1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-03-22T23:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T08:40:25.000Z", "avg_line_length": 24.4615384615, "max_line_length": 79, "alphanum_fraction": 0.5404312668, "include": true, "reason": "import numpy", "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924802053235, "lm_q2_score": 0.9372107878954105, "lm_q1q2_score": 0.9109618382016453}} {"text": "import streamlit as st \r\nimport pandas as pd \r\nimport math \r\nimport numpy as np \r\n\r\nst.title('Explore Prime Numbers') \r\nst.header('Find if a number is prime, prime numbers under a particular integer, odd/even prime numbers')\r\n\r\n#to tell if a number is prime \r\ndef is_prime(n):\r\n \"\"\"\"pre-condition: n is a nonnegative integer\r\n post-condition: return True if n is prime and False otherwise.\"\"\"\r\n if n < 2: \r\n return False;\r\n if n % 2 == 0: \r\n return n == 2 # return False\r\n k = 3\r\n while k*k <= n:\r\n if n % k == 0:\r\n return False\r\n k += 2\r\n return True\r\nisprime = st.number_input(\"Enter n an integer\",3)\r\nisprime = int(isprime)\r\nAnswer =is_prime(isprime)\r\nif Answer:\r\n s = \" is a prime number\"\r\nelse:\r\n s = \"is not a prime number\"\r\nst.write('{}'.format(isprime),s )\r\ndef even_numbers(lst):\r\n l = lst[:]\r\n for x in l:\r\n if not x%2 == 0:\r\n l.remove(x)\r\n return l\r\n\r\ndef primes(n):\r\n #https://radiusofcircle.blogspot.com/2016/06/problem-50-project-euler-solution-with-python.html\r\n is_prime = [True]*n\r\n is_prime[0] = False\r\n is_prime[1] = False\r\n is_prime[2] = True\r\n # even numbers except 2 have been eliminated\r\n for i in np.arange(3, int(n**0.5+1), 2):\r\n index = i*2\r\n while index < n:\r\n is_prime[index] = False\r\n index = index+i\r\n prime = [2]\r\n for i in np.arange(3, n, 2):\r\n if is_prime[i]:\r\n prime.append(i)\r\n return prime \r\n\r\nL = 0\r\nK = [[50,50]]\r\nfor i in range(1, 100):\r\n for j in range(100,i,-1):\r\n if i+j == 100:\r\n K.append([i,j])\r\n \r\n \r\n L+= 1\r\n\r\n\r\nn = isprime\r\n\r\nprimesundern =primes(n)\r\n\r\n\r\n \r\nif(st.button('Find prime numbers under n')):\r\n \r\n # print the BMI INDEX\r\n st.text(\"The prime numbers under n are {}\".format(primesundern ))\r\n st.text(\"There are {} prime numbers under n\".format(len(primesundern)))\r\n\r\nif(st.button('Find odd prime numbers under n')):\r\n \r\n # print the BMI INDEX\r\n st.text(\"The prime numbers under n are {}\".format(primesundern ))\r\n st.text(\"There are {} prime numbers under n\".format(len(primesundern)))\r\n\r\n\r\n\r\nif(st.button('Find even prime numbers under n')):\r\n \r\n # print the BMI INDEX\r\n st.text(\"The prime numbers under n are {}\".format(even_numbers(primesundern )))\r\n st.text(\"There are {} prime numbers under n\".format(len(primesundern)))\r\n\r\nif(st.button('Find prime numbers divisble by n under n')):\r\n \r\n # print the BMI INDEX\r\n st.text(\"The prime numbers under n are {}\".format(primesundern ))\r\n st.text(\"There are {} prime numbers under n\".format(len(primesundern)))\r\n\r\n", "meta": {"hexsha": "a4239868b77879c39062918900d4e1c07fb46a74", "size": 2722, "ext": "py", "lang": "Python", "max_stars_repo_path": "webappprimenumbers.py", "max_stars_repo_name": "NavyaSaini/web_app_prime_numbers", "max_stars_repo_head_hexsha": "30e192846a6c8c3bd0f0d6170dbd2a4c06d66c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "webappprimenumbers.py", "max_issues_repo_name": "NavyaSaini/web_app_prime_numbers", "max_issues_repo_head_hexsha": "30e192846a6c8c3bd0f0d6170dbd2a4c06d66c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "webappprimenumbers.py", "max_forks_repo_name": "NavyaSaini/web_app_prime_numbers", "max_forks_repo_head_hexsha": "30e192846a6c8c3bd0f0d6170dbd2a4c06d66c94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4949494949, "max_line_length": 105, "alphanum_fraction": 0.577149155, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668712109662, "lm_q2_score": 0.9284087985746093, "lm_q1q2_score": 0.9109239561021816}} {"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 26 19:11:24 2019\n\n@author: alankar\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n return x*(x-1)\n\ndef derv(func,x, delta=1.e-2):\n return (func(x+delta)-func(x))/delta\n\ndef fprime(x):\n return 2*x-1\n\nprint(\"f(x)=x(x-1)\\nAt x=1,\")\nprint(\"Numerical derivative (Forward Difference): %f\"%derv(f,1))\nprint(\"Analytical Derviative: %f\"%fprime(1))\nprint(\"Relative Error: %e\"%np.abs((derv(f,1)-fprime(1))/fprime(1)))\nprint(\"This arises as a truncation error as an approximation for the derivative using Forward difference.\")\n\ny = []\nfor delta in np.array([2,4,6,8,10,12,14]):\n y.append(np.abs((derv(f,1,delta=1/10**delta)-fprime(1))/fprime(1)))\n \nplt.plot(-np.array([2,4,6,8,10,12,14]),np.log10(y))\nplt.xlabel(r'$\\log_{10}(h)$', size=20)\nplt.ylabel(r'$\\log_{10}\\left(\\left|\\frac{f^{(1)}_{analytic}-f^{(1)}_{numerical}}{f^{(1)}_{analytic}}\\right|\\right)$', size=20)\nplt.title('Relative Error as a function of step size',size=20)\nplt.grid()\n#plt.savefig('error.jpg')\nplt.show()\n\n\"\"\"\nOutput\nf(x)=x(x-1)\nAt x=1,\nNumerical derivative (Forward Difference): 1.010000\nAnalytical Derviative: 1.000000\nRelative Error: 1.000000e-02\nThis arises as a truncation error as an approximation for the derivative using Forward difference.\n\"\"\"", "meta": {"hexsha": "48bb849bb3b4b68c1f3b867ce3dc3fad01aec6b0", "size": 1318, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw2/03/3.py", "max_stars_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_stars_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:47:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:05:39.000Z", "max_issues_repo_path": "hw2/03/3.py", "max_issues_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_issues_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/03/3.py", "max_forks_repo_name": "dutta-alankar/PH-354-2018-IISc-Assignment-Problems", "max_forks_repo_head_hexsha": "370dbbc447749cebe148a6ffffb48ea978b2949b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-21T17:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T02:58:56.000Z", "avg_line_length": 28.0425531915, "max_line_length": 126, "alphanum_fraction": 0.6767830046, "include": true, "reason": "import numpy", "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140254249553, "lm_q2_score": 0.9416541569322378, "lm_q1q2_score": 0.9104986114374926}} {"text": "'''\nBootstrap replicates of the mean and the SEM\n\nIn this exercise, you will compute a bootstrap estimate of the probability distribution function of the\nmean annual rainfall at the Sheffield Weather Station. Remember, we are estimating the mean annual rainfall \nwe would get if the Sheffield Weather Station could repeat all of the measurements from 1883 to 2015 over\nand over again. This is a probabilistic estimate of the mean. You will plot the PDF as a histogram, and \nyou will see that it is Normal.\n\nIn fact, it can be shown theoretically that under not-too-restrictive conditions, the value of the \nmean will always be Normally distributed. (This does not hold in general, just for the mean and a \nfew other statistics.) The standard deviation of this distribution, called the standard error of the \nmean, or SEM, is given by the standard deviation of the data divided by the square root of the number \nof data points. I.e., for a data set, sem = np.std(data) / np.sqrt(len(data)). Using hacker statistics,\nyou get this same result without the need to derive it, but you will verify this result from your\nbootstrap replicates.\n\nThe dataset has been pre-loaded for you into an array called rainfall.\n\nINSTRUCTIONS\n100XP\n-Draw 10000 bootstrap replicates of the mean annual rainfall using your draw_bs_reps() function and the\nrainfall array. Hint: Pass in np.mean for func to compute the mean.\n-As a reminder, draw_bs_reps() accepts 3 arguments: data, func, and size.\n-Compute and print the standard error of the mean of rainfall.\n-The formula to compute this is np.std(data) / np.sqrt(len(data)).\n-Compute and print the standard deviation of your bootstrap replicates bs_replicates.\n-Make a histogram of the replicates using the normed=True keyword argument and 50 bins.\n-Hit 'Submit Answer' to see the plot!\n'''\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef draw_bs_reps(data, func, size=1):\n \"\"\"Draw bootstrap replicates.\"\"\"\n\n # Initialize array of replicates: bs_replicates\n bs_replicates = np.empty(size)\n\n # Generate replicates\n for i in range(size):\n bs_replicates[i] = bootstrap_replicate_1d(data, func)\n\n return bs_replicates\n\n# Take 10,000 bootstrap replicates of the mean: bs_replicates\nbs_replicates = draw_bs_reps(rainfall, np.mean, size=10000)\n\n# Compute and print SEM\nsem = np.std(rainfall) / np.sqrt(len(rainfall))\nprint(sem)\n\n# Compute and print standard deviation of bootstrap replicates\nbs_std = np.std(bs_replicates)\nprint(bs_std)\n\n# Make a histogram of the results\n_ = plt.hist(bs_replicates, bins=50, normed=True)\n_ = plt.xlabel('mean annual rainfall (mm)')\n_ = plt.ylabel('PDF')\n\n# Show the plot\nplt.show()\n", "meta": {"hexsha": "d55c3134c896e2439d0cf287017fcc9eb935bbe1", "size": 2671, "ext": "py", "lang": "Python", "max_stars_repo_path": "Data Science With Python/16-statistical-thinking-in-python-(part-2)/2-bootstrap-confidence=intervals/bootstrap-replicates-of-the-mean-and-the-SEM.py", "max_stars_repo_name": "aimanahmedmoin1997/DataCamp", "max_stars_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-12T04:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T00:40:28.000Z", "max_issues_repo_path": "Data Science With Python/16-statistical-thinking-in-python-(part-2)/2-bootstrap-confidence=intervals/bootstrap-replicates-of-the-mean-and-the-SEM.py", "max_issues_repo_name": "aimanahmedmoin1997/DataCamp", "max_issues_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Science With Python/16-statistical-thinking-in-python-(part-2)/2-bootstrap-confidence=intervals/bootstrap-replicates-of-the-mean-and-the-SEM.py", "max_forks_repo_name": "aimanahmedmoin1997/DataCamp", "max_forks_repo_head_hexsha": "c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-11-06T17:43:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T21:08:16.000Z", "avg_line_length": 41.0923076923, "max_line_length": 108, "alphanum_fraction": 0.7678771996, "include": true, "reason": "import numpy", "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112959, "lm_q2_score": 0.9416541589789722, "lm_q1q2_score": 0.9104986098253606}} {"text": "\"\"\"\nExample: Cafe Java Arrival Time Distribution and Process Generator.\n\nThis example develops a continuous process generator for arrival times \nobserved in Cafe Java.\n\n@author: Paul T. Grogan \n\"\"\"\n\n# import the python3 behavior for importing, division, and printing in python2\nfrom __future__ import absolute_import, division, print_function\n\n# import the numpy package and refer to it as `np`\n# see http://docs.scipy.org/doc/numpy/reference/ for documentation\nimport numpy as np\n\n# import the matplotlib pyplot package and refer to it as `plt`\n# see http://matplotlib.org/api/pyplot_api.html for documentation\nimport matplotlib.pyplot as plt\n\n# import the scipy stats package and refer to it as `stats`\n# see http://docs.scipy.org/doc/scipy-0.14.0/reference/stats.html for docs\nimport scipy.stats as stats\n\n_lambda = 1/2 # customers per minute\n\n# define a linear space between 0 and 10\nplot_x = np.linspace(0,10)\n# define PDF and CDF functions from derived formulas\npdf = _lambda*np.exp(-_lambda*plot_x)\ncdf = 1-np.exp(-_lambda*plot_x)\n\n# create a new figure for a PDF plot\nplt.figure()\n# plot the PDF using a blue line (-b)\nplt.plot(plot_x, pdf, '-b')\n# plot the PDF using the built-in function using a dashed black line (--k)\nplt.plot(plot_x, stats.expon.pdf(plot_x, scale=1./_lambda), '--k')\nplt.xlabel('Inter-arrival Time x (minutes)')\nplt.ylabel('f(x)')\nplt.title('PDF for Cafe Java Inter-arrival Time')\n\n# create a new figure for a CDF plot\nplt.figure()\n# plot the CDF using a blue line (-b)\nplt.plot(plot_x, cdf, '-b')\n# plot the CDF using the built-in function using a dashed black line (--k)\nplt.plot(plot_x, stats.expon.cdf(plot_x, scale=1./_lambda), '--k')\nplt.xlabel('Inter-arrival Time x (minutes)')\nplt.ylabel('F(x)')\nplt.title('CDF for Cafe Java Inter-arrival Time')\n\n# define a function to compute arrival times using inverse transform method\ndef generate_arrival_ivt():\n \"\"\"Generates an arrival time following the inverse transform method.\n \n Returns:\n arrival (float): the time until the next arrival \n \"\"\"\n r = np.random.rand()\n return -np.log(1-r)/_lambda\n \"\"\"\n note: the code above could be replaced with the built-in process generator:\n \n return np.random.exponential(1/_lambda)\n \"\"\"\n\n# define number of samples\nnum_samples = 1000\n\n# fill the samples arrays with samples from the generators\nsamples_ivt = [generate_arrival_ivt() for i in range(num_samples)]\n\n# create a new figure to display a histogram of results\nplt.figure()\n# plot a histogram of samples, using bins between 0 and 10\nplt.hist(samples_ivt, bins=range(10), color='blue', label='IVT Samples')\n# overlay a plot of the theoretical number of samples computed from PDF\nplt.plot(plot_x, stats.expon.pdf(plot_x, scale=1./_lambda)*num_samples,\n '-k', label='Theoretical')\nplt.xlabel('Inter-arrival Time Bin (minutes)')\nplt.ylabel('Count')\nplt.title('Histogram for Inter-arrival Time Samples (n={})'.format(num_samples))\nplt.legend()", "meta": {"hexsha": "e23eb5e0a70386bea95c6d0f1dc4dc1429e8a4b5", "size": 2988, "ext": "py", "lang": "Python", "max_stars_repo_path": "previous/week3/arrivalGeneratorIVT.py", "max_stars_repo_name": "code-lab-org/sys611", "max_stars_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-07T03:52:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T18:16:16.000Z", "max_issues_repo_path": "previous/week3/arrivalGeneratorIVT.py", "max_issues_repo_name": "code-lab-org/sys611", "max_issues_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "previous/week3/arrivalGeneratorIVT.py", "max_forks_repo_name": "code-lab-org/sys611", "max_forks_repo_head_hexsha": "3b8c46788dee629a9f2d6b7f84373e041b918ff0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-02-12T01:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T18:05:27.000Z", "avg_line_length": 35.5714285714, "max_line_length": 80, "alphanum_fraction": 0.733601071, "include": true, "reason": "import numpy,import scipy", "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9763105335255604, "lm_q2_score": 0.9324533144915912, "lm_q1q2_score": 0.9103639929589625}} {"text": "import numpy as np\nimport numpy.linalg as linalg\n\n\ndef compute_Z(X, centering=True, scaling=False):\n Z = X.astype(np.double)\n if (centering == True):\n # calculate the mean of each column (axis = 0)\n col_averages = np.mean(X, axis=0)\n for i in range(X.shape[1]):\n Z[:,i] = X[:,i] - col_averages[i]\n \n if (scaling == True):\n # calculate the standard deviation by column (axis = 0)\n col_std = np.std(X, axis=0)\n \n # print(X.shape[1])\n # print(X.shape[0])\n for j in range(X.shape[1]):\n for m in range(X.shape[0]):\n Z[m][j] = Z[m][j] / col_std[j]\n return Z\n\ndef compute_covariance_matrix(Z):\n cov = np.matmul(Z.transpose(),Z)\n # print(Z.transpose())\n return cov\n\n\ndef find_pcs(COV):\n eigenValues, eigenVectors = linalg.eig(COV)\n idx = eigenValues.argsort()[::-1]\n eigenValues = eigenValues[idx]\n eigenVectors = eigenVectors[:,idx]\n return eigenValues, eigenVectors\n\n\ndef project_data(Z, PCS, L, k, var):\n if ((k==0) and (var ==0)):\n print(\"Error inputs\")\n return 0\n\n if (not(k==0) and not(var ==0)):\n print(\"Error inputs\")\n return 0\n\n if (var == 0):\n if ((k < 0) or (k>len(PCS[0]))):\n print(\"Error input parameters due to k\")\n return 0\n space = np.zeros((len(PCS),k), dtype=complex)\n for i in range(len(PCS)):\n for j in range(k):\n space[i][j] = PCS[i][j]\n pro_data = np.matmul(Z,space)\n return pro_data\n\n if (k == 0):\n if ((var < 0.0) or (var>1.0)):\n print(\"Error input parameters due to var\")\n return 0\n S = np.sum(L)\n check = 0.0\n for m in range(len(L)):\n check += L[m]\n if (check/S >= var):\n space = np.zeros((len(PCS),m+1), dtype=complex)\n for i in range(len(PCS)):\n for j in range(m+1):\n space[i][j] = PCS[i][j]\n pro_data = np.matmul(Z,space)\n return pro_data\n\n\n\n# if __name__ == '__main__':\n \n\n # X = np.array([[-1,-1], [-1,1], [1,-1], [1,1]])\n X = np.array([[-1,-1], [-1,1], [1,-1], [1,1], [2,6]])\n\n Z = compute_Z(X)\n COV = compute_covariance_matrix(Z)\n L, PCS = find_pcs(COV)\n Z_star = project_data(Z,PCS, L, 0, 1)\n print(Z_star)\n\n\n\n ", "meta": {"hexsha": "8ee499d33aee52a7f8ed7f7b3a15c03d71c1ebcd", "size": 2146, "ext": "py", "lang": "Python", "max_stars_repo_path": "machine_learning/project4/pca.py", "max_stars_repo_name": "buivn/Learning", "max_stars_repo_head_hexsha": "27cd468512c9d6640b5dcfecb00cd76ee6686847", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "machine_learning/project4/pca.py", "max_issues_repo_name": "buivn/Learning", "max_issues_repo_head_hexsha": "27cd468512c9d6640b5dcfecb00cd76ee6686847", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "machine_learning/project4/pca.py", "max_forks_repo_name": "buivn/Learning", "max_forks_repo_head_hexsha": "27cd468512c9d6640b5dcfecb00cd76ee6686847", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8444444444, "max_line_length": 59, "alphanum_fraction": 0.5610438024, "include": true, "reason": "import numpy", "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542864252023, "lm_q2_score": 0.9489172574450577, "lm_q1q2_score": 0.9101580549412743}} {"text": "from math import sqrt\n\nimport numpy as np\nimport pandas as pd\n\ndef squared_error(prediction, observation):\n \"\"\"\n Calculates the squared error.\n\n Args:\n prediction - the prediction from our linear regression model\n observation - the observed data point\n Returns:\n The squared error\n \"\"\"\n return (observation - prediction) ** 2\n\ndef sgd_fit(x, y, learning_rate, epochs):\n \"\"\"\n Calculates the intercept and slope parameters using SGD for\n a linear regression model.\n\n Args:\n x - feature array\n y - response array\n learning_rate - learning rate\n epochs - the number of epochs to use in the SGD loop\n Returns:\n The intercept and slope parameters and the sum of\n squared error for the last epoch\n \"\"\"\n\n # initialize the slope and intercept\n slope = 0.0\n intercept = 0.0\n\n # set the number of observations in the data\n N = float(len(y))\n\n # loop over the number of epochs\n for i in range(epochs):\n\n # calculate our current predictions\n predictions = (slope * x) + intercept\n \n # calculate the sum of squared errors for this epoch\n error = 0.0\n for idx, p in enumerate(predictions):\n error += squared_error(p, y[idx])\n error = error/N\n\n # calculate the gradients for the slope and intercept\n slope_gradient = -(2/N) * sum(x * (y - predictions))\n intercept_gradient = -(2/N) * sum(y - predictions)\n \n # update the slope and intercept\n slope = slope - (learning_rate * slope_gradient)\n intercept = intercept - (learning_rate * intercept_gradient)\n\n return intercept, slope, error\n\ndef ols_fit(x, y):\n \"\"\"\n Calculates the intercept and slope parameters using OLS for\n a linear regression model.\n\n Args:\n x - feature array\n y - response array\n Returns:\n The intercept and slope parameters\n \"\"\"\n \n # calculate the mean of x and y\n mean_x = np.mean(x)\n mean_y = np.mean(y)\n \n # Using the derived OLS formula to calculate\n # the intercept and slope.\n numerator = 0\n denominator = 0\n for i in range(len(x)):\n numerator += (x[i] - mean_x) * (y[i] - mean_y)\n denominator += (x[i] - mean_x) ** 2\n slope = numerator / denominator\n intercept= mean_y - (slope * mean_x)\n\n return intercept, slope\n\ndef main():\n \n # import the data\n data = pd.read_csv('../data/training.csv')\n \n # fit our model using our various implementations\n int_sgd, slope_sgd, _ = sgd_fit(data['TV'].values, data['Sales'].values, 0.1, 1000)\n int_ols, slope_ols = ols_fit(data['TV'].values, data['Sales'].values)\n\n # output the results\n delim = \"-----------------------------------------------------------------\"\n print(\"\\nOLS\\n{delim}\\n intercept: {intercept}, slope: {slope}\"\n .format(delim=delim, intercept=int_ols, slope=slope_ols))\n print(\"\\nSGD\\n{delim}\\n intercept: {intercept}, slope: {slope}\"\n .format(delim=delim, intercept=int_sgd, slope=slope_sgd))\n print(\"\")\n\nif __name__ == \"__main__\":\n main()\n\n", "meta": {"hexsha": "617d89d4bb7e0821dd283d4a1228dbd2faf3a334", "size": 3142, "ext": "py", "lang": "Python", "max_stars_repo_path": "day1/session2/example2/main.py", "max_stars_repo_name": "dwhitena/ai-classroom", "max_stars_repo_head_hexsha": "5ccac943c01a81c82fecd04a00ce96bac220d315", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-05-06T07:49:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-31T21:19:18.000Z", "max_issues_repo_path": "day1/session2/example2/main.py", "max_issues_repo_name": "saibaldas/ai-classroom", "max_issues_repo_head_hexsha": "5ccac943c01a81c82fecd04a00ce96bac220d315", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day1/session2/example2/main.py", "max_forks_repo_name": "saibaldas/ai-classroom", "max_forks_repo_head_hexsha": "5ccac943c01a81c82fecd04a00ce96bac220d315", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-09T20:33:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T04:37:24.000Z", "avg_line_length": 28.5636363636, "max_line_length": 87, "alphanum_fraction": 0.6075747931, "include": true, "reason": "import numpy", "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226254066621, "lm_q2_score": 0.9314625055410722, "lm_q1q2_score": 0.910059942631606}} {"text": "import numpy as np\nfrom numpy.linalg import eig\n\nif __name__ == \"__main__\":\n A1 = np.array([[4, -2],\n [1, 1]])\n eigenvalues1, eig_en_vectors1 = eig(A1)\n print(eigenvalues1)\n print(eig_en_vectors1)\n print()\n\n # 关于y=x翻转\n A2 = np.array([[0, 1],\n [1, 0]])\n eigenvalues2, eig_en_vectors2 = eig(A2)\n print(eigenvalues2)\n print(eig_en_vectors2)\n print()\n\n # 旋转90°\n A3 = np.array([[0, -1],\n [1, 0]])\n eigenvalues3, eig_en_vectors3 = eig(A3)\n print(eigenvalues3)\n print(eig_en_vectors3)\n print()\n\n # 几何重数为1\n A4 = np.array([[3, 1],\n [0, 3]])\n eigenvalues4, eig_en_vectors4 = eig(A4)\n print(eigenvalues4)\n print(eig_en_vectors4)\n print()\n", "meta": {"hexsha": "5ddfd58ea8f8660c5bdb74ecbb3929f9dacdba54", "size": 768, "ext": "py", "lang": "Python", "max_stars_repo_path": "main_eigen.py", "max_stars_repo_name": "violet-Bin/LinearAlgebra", "max_stars_repo_head_hexsha": "f3514ff12f91ad6a0e64dbdf521a8001fd4bf4c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-10T12:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-10T12:46:04.000Z", "max_issues_repo_path": "main_eigen.py", "max_issues_repo_name": "violet-Bin/LinearAlgebra", "max_issues_repo_head_hexsha": "f3514ff12f91ad6a0e64dbdf521a8001fd4bf4c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main_eigen.py", "max_forks_repo_name": "violet-Bin/LinearAlgebra", "max_forks_repo_head_hexsha": "f3514ff12f91ad6a0e64dbdf521a8001fd4bf4c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9428571429, "max_line_length": 43, "alphanum_fraction": 0.5481770833, "include": true, "reason": "import numpy,from numpy", "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517462851321, "lm_q2_score": 0.9304582487448422, "lm_q1q2_score": 0.9100363150302988}} {"text": "import numpy as np\nfrom checker.fault import get_fault\n\nnp.set_printoptions(suppress=True)\n\n\ndef solve_jacobi(matrix_a: list, vector_b: list, epsilon=10 ** (-6)) -> list:\n \"\"\"\n Solve by Jacobi method(simple iteration)\n :param matrix_a: start matrix\n :param vector_b: start vector\n :param epsilon: number for comparing\n :return: solution vector\n \"\"\"\n solution_vector = [0 for _ in range(len(matrix_a[0]))]\n\n matrix_c = []\n vector_d = []\n # Create matrix C and vector D\n for i in range(len(matrix_a)):\n element_d = vector_b[i] / matrix_a[i][i]\n vector_d.append(element_d)\n\n element_c = []\n for j in range(len(matrix_a[0])):\n if i == j:\n element_c.append(0)\n else:\n element_c.append((-1) * matrix_a[i][j] / matrix_a[i][i])\n matrix_c.append(element_c)\n\n iterations = 0\n tmp = 0\n # Start the main algorithm\n while True:\n divs = []\n left_part = np.dot(matrix_c, solution_vector)\n for i in range(len(solution_vector)):\n x_next = left_part[i] + vector_d[i]\n divs.append(abs(x_next - solution_vector[i]))\n solution_vector[i] = x_next\n # Check if we need to stop\n if max(divs) < epsilon:\n print(f'Last result: {np.matrix(solution_vector).round(6)}')\n # It's time to stop!\n break\n else:\n if tmp < 3:\n print(f'Temporary result: {np.matrix(solution_vector).round(6)}')\n tmp += 1\n print(f'Residual vector: {np.matrix(np.subtract(vector_b, np.dot(matrix_a, solution_vector)), float).round(6)}')\n iterations += 1\n print(f'Iterations: {iterations}')\n return solution_vector\n\n\na = [[4.4944, 0.1764, 1.7956, 0.7744],\n [0.1764, 15.6025, 3.4969, 0.1849],\n [1.7956, 3.4969, 8.8804, 0.2116],\n [0.7744, 0.1849, 0.2116, 19.7136]]\nb = [31.97212, 9.18339, 19.51289, 51.39451]\nprint(f'Matrix A:', np.matrix(a).round(6))\nprint(f'Vector b:', b)\nsol = solve_jacobi(a.copy(), b.copy())\nsol_np = np.linalg.solve(a, b)\nprint(f'Our solution: {np.matrix(sol).round(6)}')\nprint(f'Residual vector: {np.matrix(np.subtract(b, np.dot(a, sol))).round(6)}')\nprint(f'NumPy solution: {sol_np}')\nprint(f'Residual vector for NumPy: {np.matrix(np.subtract(b, np.dot(a, sol_np))).round(6)}')\nprint('Fault:', round(get_fault(sol, sol_np), 6))\n", "meta": {"hexsha": "baa5f6ecdca9d54c97842f57a35e8f745462ab26", "size": 2417, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lab3/jacobi.py", "max_stars_repo_name": "mezgoodle/numericalMethods_labs", "max_stars_repo_head_hexsha": "1631b50ae32ff1a81d63a2216a8015df4e2abb84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-02T11:24:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T11:24:46.000Z", "max_issues_repo_path": "Lab3/jacobi.py", "max_issues_repo_name": "mezgoodle/numericalMethods_labs", "max_issues_repo_head_hexsha": "1631b50ae32ff1a81d63a2216a8015df4e2abb84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab3/jacobi.py", "max_forks_repo_name": "mezgoodle/numericalMethods_labs", "max_forks_repo_head_hexsha": "1631b50ae32ff1a81d63a2216a8015df4e2abb84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0422535211, "max_line_length": 124, "alphanum_fraction": 0.5957798924, "include": true, "reason": "import numpy", "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877684006775, "lm_q2_score": 0.9372107940336021, "lm_q1q2_score": 0.9097390541815042}} {"text": "# Trigonometric Functions\nimport numpy as np \na = np.array([0,30,45,60,90]) \n\nprint ('Sine of different angles:') \n# Convert to radians by multiplying with pi/180 \nprint (np.sin(a*np.pi/180)) \nprint ('\\n') \n\nprint ('Cosine values for angles in array:') \nprint (np.cos(a*np.pi/180))\nprint ('\\n') \n\nprint ('Tangent values for given angles:') \nprint (np.tan(a*np.pi/180))\n\nimport numpy as np \na = np.array([0,30,45,60,90]) \n\nprint ('Array containing sine values:') \nsin = np.sin(a*np.pi/180) \nprint (sin)\nprint ('\\n') \n\nprint ('Compute sine inverse of angles. Returned values are in radians.') \ninv = np.arcsin(sin) \nprint (inv)\nprint ('\\n') \n\nprint ('Check result by converting to degrees:') \nprint (np.degrees(inv))\nprint ('\\n') \n\nprint ('arccos and arctan functions behave similarly:') \ncos = np.cos(a*np.pi/180) \nprint (cos) \nprint ('\\n') \n\nprint ('Inverse of cos:') \ninv = np.arccos(cos) \nprint (inv) \nprint ('\\n') \n\nprint ('In degrees:') \nprint (np.degrees(inv)) \nprint ('\\n') \n\nprint ('Tan function:') \ntan = np.tan(a*np.pi/180) \nprint (tan)\nprint ('\\n') \n\nprint ('Inverse of tan:') \ninv = np.arctan(tan) \nprint (inv)\nprint ('\\n') \n\nprint ('In degrees:') \nprint (np.degrees(inv)) \n\n# Functions for Rounding\nimport numpy as np \na = np.array([1.0,5.55, 123, 0.567, 25.532]) \n\nprint ('Original array:') \nprint (a) \nprint ('\\n') \n\nprint ('After rounding:') \nprint (np.around(a)) \nprint (np.around(a, decimals = 1)) \nprint (np.around(a, decimals = -1))\n\nimport numpy as np \na = np.array([-1.7, 1.5, -0.2, 0.6, 10]) \n\nprint ('The given array:')\nprint (a) \nprint ('\\n') \n\nprint ('The modified array:') \nprint (np.floor(a))\n\nimport numpy as np \na = np.array([-1.7, 1.5, -0.2, 0.6, 10]) \n\nprint ('The given array:') \nprint (a)\nprint ('\\n') \n\nprint ('The modified array:') \nprint (np.ceil(a))", "meta": {"hexsha": "d713e9240809082141ea52a817b6d515d24e7b28", "size": 1797, "ext": "py", "lang": "Python", "max_stars_repo_path": "numpy/mathfunction.py", "max_stars_repo_name": "praveenpmin/Python", "max_stars_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numpy/mathfunction.py", "max_issues_repo_name": "praveenpmin/Python", "max_issues_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numpy/mathfunction.py", "max_forks_repo_name": "praveenpmin/Python", "max_forks_repo_head_hexsha": "513fcde7430b03a187e2c7e58302b88645388eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5326086957, "max_line_length": 74, "alphanum_fraction": 0.6260434057, "include": true, "reason": "import numpy", "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9766692352660529, "lm_q2_score": 0.931462511724468, "lm_q1q2_score": 0.909730779004933}} {"text": "import numpy as np\r\nfrom numpy.linalg import qr\r\nnp.set_printoptions(precision=2, suppress=True) # It is set to display & secure the output with 4 decimals\r\n\r\ndef qr_factorization(A): #Defining the function\r\n m, n = A.shape\r\n Q = np.zeros((m, n))\r\n R = np.zeros((n, n))\r\n\r\n for j in range(n):\r\n v = A[:, j]\r\n\r\n for i in range(j):\r\n q = Q[:, i]\r\n R[i, j] = q.dot(v)\r\n v = v - R[i, j] * q\r\n\r\n norm = np.linalg.norm(v)\r\n Q[:, j] = v / norm\r\n R[j, j] = norm\r\n return Q, R\r\n\r\na = np.array([[0,2],\r\n [2,3]])\r\n\r\nn = int(input(\"How many iterations you want?\"))\r\nprint(\"\\n Given Matrix : A = \",a)\r\nprint(\"\\n QR Factorization of A : \",qr_factorization(a))\r\n\r\ni=0 #Initial Iteration\r\nwhile i 1000000.\n#\n# Authors: Philipp Schuette, Daniel Schuette\n# Date: 2018/09/24\n# License: MIT (see ../LICENSE.md)\nimport time\n\nimport numpy as np\n\n\ndef slow_divisible(a=3, b=5, target=1000):\n \"\"\"\n this function calculates the sum of all integers from 0 to\n `target' that are divisible by `a' or `b' with a remander\n of 0\n this is a slow implementation of the algorithm\n -------------------------\n params:\n a, b - the integers that are used for the modulo operation\n target - the interval over which to calculate the sum\n \"\"\"\n sum = 0\n for i in range(target):\n if (i % 3) == 0:\n sum += i\n elif (i % 5) == 0:\n sum += i\n return sum\n\n\ndef fast_summation(x, target):\n \"\"\"\n this function calculates the sum of all integers from 0 to\n `target' that are divisible by `x' with a remander of 0\n this is a fast implementation of the algorithm\n -------------------------\n params:\n x - the integer that is used for the modulo operation\n target - the interval over which to calculate the sum\n \"\"\"\n n = (target - 1) // x\n sum = x * n * (n + 1) / 2\n return sum\n\n\ndef fast_divisible(a=3, b=5, target=1000):\n \"\"\"\n this function calculates the project euler problem 1\n solution using a fast solution\n `fast_summation()' is used to do so\n \"\"\"\n sum = (fast_summation(a, target) + fast_summation(b, target) -\n fast_summation(a * b, target))\n return sum\n\n\nif __name__ == \"__main__\":\n # get a target from the user\n target = int(input(\"please provide a positive integer: \"))\n\n # time the slow function\n slow_start = time.time()\n slow_solution = slow_divisible(target=target)\n slow_end = time.time()\n slow_time = slow_end - slow_start\n\n # time the fast function\n fast_start = time.time()\n fast_solution = fast_divisible(target=target)\n fast_end = time.time()\n fast_time = fast_end - fast_start\n\n # print the results\n print(\"slow solution: {}\\nfast solution: {}\".format(\n slow_solution,\n fast_solution,\n ))\n print(\"slow time: {}s\\nfast time: {}s\".format(\n np.round(slow_time, 6), np.round(fast_time, 6)))\n", "meta": {"hexsha": "0325104a513db6e84a84e7795fa87f21e52972c4", "size": 2654, "ext": "py", "lang": "Python", "max_stars_repo_path": "py_src/problem001.py", "max_stars_repo_name": "PhilippSchuette/projecteuler", "max_stars_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-24T14:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T01:57:12.000Z", "max_issues_repo_path": "py_src/problem001.py", "max_issues_repo_name": "PhilippSchuette/projecteuler", "max_issues_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2018-09-24T14:18:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-08T07:03:31.000Z", "max_forks_repo_path": "py_src/problem001.py", "max_forks_repo_name": "PhilippSchuette/projecteuler", "max_forks_repo_head_hexsha": "b74f76e8f27769d5cfc4227ccfb272d0a83ef587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-01T14:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T01:57:53.000Z", "avg_line_length": 29.4888888889, "max_line_length": 69, "alphanum_fraction": 0.6296156745, "include": true, "reason": "import numpy", "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.9546474150908866, "lm_q1q2_score": 0.9086937670627669}} {"text": "from numpy import array, zeros, sqrt\n\ndef decomposition(A):\n N = len(A)\n L = zeros((N,N))\n U = zeros((N,N))\n\n for j in range(N): # j = 0 to N-1\n\n # Upper Triangular\n for i in range(j+1): # i = 0 to j\n\n U[i,j] = A[i,j] - sum(U[:i,j] * L[i,:i]) # k = 0 to i-1\n\n # Lower Triangular\n L[j,j] = 1 # i = j, Diagonal 1\n\n for i in range(j+1, N): # i = j+1 to N-1\n\n L[i,j] = (A[i,j] - sum(U[:j,j]*L[i,:j]))/U[j,j] # k = 0 to j-1\n\n print('LU Decomposition:')\n print('[L] =\\n', L, sep='')\n print('[U] =\\n', U, sep='', end='\\n\\n')\n return L, U\n\n\ndef solveLU(A, B):\n L, U = decomposition(A)\n N = len(L)\n \n X = zeros(N)\n Y = zeros(N)\n\n # Forward Substitution\n for i in range(N): # i = 0 to N-1\n Y[i] = (B[i] - sum(L[i,:i] * Y[:i])) # j = 0 to i-1\n\n # sumj = 0\n # for j in range(i):\n # sumj += L[i,j] * Y[j]\n # Y[i] = (B[i] - sumj)\n\n # Backward Substitution\n for i in range(N-1, -1, -1): # i = N-1 to 0\n X[i] = (Y[i] - sum(U[i,i+1:] * X[i+1:])) / U[i,i] # j = i+1 to N-1\n\n # sumj = 0\n # for j in range(i+1, N):\n # sumj += U[i,j] * X[j]\n # X[i] = (Y[i] - sumj) / U[i,i]\n\n return X\n\n\n# System of Equations\n\nA = array([[3, -.1, -.2],\n [.1, 7, -.3],\n [.3, -.2, 10]], float)\nB = array([10.3, 33.6, 60.2], float)\n\nN = len(A)\n\n\nX = solveLU(A, B)\n\nprint(\"The Solution of the System:\")\nfor i in range(N):\n print('X[', i+1, '] = ', round(X[i], 6), sep='')\n\n\n'''\nDecomposition: [A] = [L][U] # [L][U] ≠ [U][L] Not commutative\n\n│a11 a12 a13 ... a1n│ │L11 0 0 ... 0 ││U11 U12 U13 ... U1n│\n│a21 a22 a23 ... a2n│ │L21 L22 0 ... 0 ││ 0 U22 U23 ... U2n│\n│a31 a32 a33 ... a3n│ = │L31 L32 L33 ... 0 ││ 0 0 U33 ... U3n│\n│... ... ... ... ...│ │... ... ... ... ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│ │Ln1 Ln2 Ln3 ... Lnn││ 0 0 0 ... Unn│\n\nFor Doolittle: Lii = 1 All elements on main diagonal of [L] are 1\n\n│a11 a12 a13 ... a1n│ │ 1 0 0 ... 0 ││U11 U12 U13 ... U1n│\n│a21 a22 a23 ... a2n│ │L21 1 0 ... 0 ││ 0 U22 U23 ... U2n│\n│a31 a32 a33 ... a3n│ = │L31 L32 1 ... 0 ││ 0 0 U33 ... U3n│\n│... ... ... ... ...│ │... ... ... 1 ...││... ... ... ... ...│\n│an1 an2 an3 ... ann│ │Ln1 Ln2 Ln3 ... 1 ││ 0 0 0 ... Unn│\n\n│a11 a12 a13 ... a1n│\n│a21 a22 a23 ... a2n│\n│a31 a32 a33 ... a3n│ =\n│... ... ... ... ...│\n│an1 an2 an3 ... ann│\n\n│U11 U12 U13 ... U1n │\n│U11L21 U12L21+U22 U13L21+U23 ... U1nL21+U2n │\n│U11L31 U12L31+U22L32 U13L31+U23L32+U33 ... U1nL31+U2nL32+U3n │\n│ ... ... ... ... ... │\n│U11Ln1 U12Ln1+U22Ln2 U13Ln1+U23Ln2+U33Ln3 ... U1nLn1+U2nLn2+U3nLn3+...+Unn│\n\n U1jLi1 U1jLi1+U2jLi2 U1jLi1+U2jLi2+U3jLi3 ... U1jLi1+U2jLi2+U3jLi3+...+Unj\n\n where i = 1 to n, j = 1 to n, k = 1 to j\n\n\nU11 = a11 U12 = a12 U13 = a13 ...\nL21 = a21/U11 U22 = a22-U12L21 U23 = a23-U13L21 ...\nL31 = a31/U11 L32 = (a32-U12L31)/U22 U33 = a33-U13L31-U23L32 ...\nLn1 = an1/U11 Ln2 = (an3-U12Ln1)/U22 Ln3 = (an3-U13L31-U23L32)/U33 ...\n\nUij = aij Uij = aij-U1jLi1 Uij = aij-U1jLi1-U2jLi2\nLij = aij/Ujj Lij = (aij-U1jLi1)/Ujj Lij = (aij-U1jLi1-U2jLi2)/Ujj \n\nLjj = 1 j = 1 to n\nUij = aij - ∑ Ukj*Lik i = 1 to j, k = 1 to i-1\nLij = (aij - ∑ Ukj*Lik)/Ujj i = j+1 to n, k = 1 to j-1\n\nFor U1j there is no ∑ and is implimented by k = 1 to 1-1, not entering k loop\nFor Li1 there is no ∑ and is implimented by k = 1 to 1-1, not entering k loop\n\n\nSubstitution: [A]{X}={B} => [L][U]{X}={B} => [U]{X}={y} and [L]{y}={B}\n\nForward Substitution: [L]{y}={B}\n\n│ 1 0 0 ... 0 ││y1│ │b1│\n│L21 1 0 ... 0 ││y2│ │b2│\n│L31 L32 1 ... 0 ││y3│ = │b3│\n│... ... ... ... ...││……│ │……│\n│Ln1 Ln2 Ln3 ... 1 ││yn│ │bn│\n\ny1 = b1\ny2 = (b2 - L21y1)\ny3 = (b3 - L31y1 - L32y2)\nyn = (bn - Ln1y1 - Ln2y2 - ... - L[n,n-1]y[n-1])\n\nyi = (bi - ∑ Lij*yj) , i = 1 to n, j = 1 to i-1\n\nFor y1 there is no ∑ and is implimented by j = 1 to 1-1, not entering j loop\n\nBackward Substitution: [U]{X}={y}\n\n│U11 U12 U13 ... U1n││x1│ │y1│\n│ 0 U22 U23 ... U2n││x2│ │y2│\n│ 0 0 U33 ... U3n││x3│ = │y3│\n│... ... ... ... ...││……│ │……│\n│ 0 0 0 ... Unn││xn│ │yn│\n\nxn = yn / Unn\nx3 = (y3 - U34*x4) / U33\nx2 = (y2 - U23*x3 - U24*x4) / U22\nx1 = (y1 - U12*x2 - U13*x3 - U14*x4) / U11\nxi = (yi - Uij*xj - Uij*xj - Uij*xj) / Uii\n\nxi = (yi - ∑ Uij*xj) / Uii , i = n to 1, j = i+1 to n\n\nFor xn there is no ∑ and is implimented by j = n+1 to n, not entering j loop\n\n'''\n", "meta": {"hexsha": "379a58cc40fc1d64cc502bba08ec99d49ab3eaef", "size": 4987, "ext": "py", "lang": "Python", "max_stars_repo_path": "5. Systems of Linear Equations/4. Doolittle's (Lii=1) Triangularization (Factorization or LU Decomposition) Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5. Systems of Linear Equations/4. Doolittle's (Lii=1) Triangularization (Factorization or LU Decomposition) Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5. Systems of Linear Equations/4. Doolittle's (Lii=1) Triangularization (Factorization or LU Decomposition) Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9751552795, "max_line_length": 79, "alphanum_fraction": 0.41568077, "include": true, "reason": "from numpy", "num_tokens": 2254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347890464284, "lm_q2_score": 0.9324533046369554, "lm_q1q2_score": 0.9086149391995567}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# calculates the y value of a function given its lagrange expansion\ndef lagrange_i(x_i, x_list, y_list):\n y_i = 0\n for j in range(len(x_list)):\n l = 1\n for m in range(len(x_list)):\n if m != j:\n l *= (x_i - x_list[m])/(x_list[j]-x_list[m])\n y_i = y_i + y_list[j]*l\n return y_i\n\n\n# calculates the Lagrange Extrapolation of a discrete function given a list of x coordinates,\n# corresponding y coordinates, and the number of point wanted to make the extrapolation\ndef lagr_interpol(x_list, y_list, num_points):\n x_pts = np.linspace(x_list[0], x_list[len(x_list)-1], num_points)\n y_pts = np.zeros(shape=(num_points, 1))\n for i in range(num_points):\n y_i = lagrange_i(x_pts[i], x_list, y_list)\n y_pts[i] = y_i\n return x_pts, y_pts\n\n\nif __name__ == '__main__':\n # list of H and B values provided in the assignment\n B = [0, 0.2, 0.4, 0.6, 0.8, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9]\n H = [0, 14.7, 36.5, 71.7, 121.4, 197.4, 256.2, 348.7, 540.6, 1062.8, 2318.0, 4781.9, 8687.4, 13924.3, 22650.2]\n\n B_1 = B[0:6] # subdomain of B for Q1a)\n H_1 = H[0:6] # subdomain of H for Q1a)\n ans = lagr_interpol(B_1, H_1, 100)\n x1, y1 = ans\n\n B_2 = [0, 1.3, 1.4, 1.7, 1.8, 1.9] # subdomain of B for Q1b)\n H_2 = [0, 540.6, 1062.8, 8687.4, 13924.3, 22650.2] # subdomain of H for Q1b)\n\n ans2 = lagr_interpol(B_2, H_2, 100)\n x2, y2 = ans2\n\n# comment these out to test for the question 1 a), or 1b)\n plt.title(\"Question 1a\")\n plt.xlabel(\"B (T)\")\n plt.ylabel(\"H (A/m)\")\n plt.plot(x1, y1, color=\"black\", label=\"Lagrange Interpolation\")\n plt.plot(B_1, H_1, label='Original Values')\n plt.legend(loc=\"upper left\")\n plt.show()\n\n# uncomment to see 1b) answer\n# plt.title(\"Question 1b\")\n# plt.xlabel(\"B (T)\")\n# plt.ylabel(\"H (A/m)\")\n# plt.plot(x2, y2, color=\"black\", label=\"Lagrange Interpolation\")\n# plt.plot(B_2, H_2, label='Original Values')\n# plt.legend(loc=\"upper left\")\n# plt.show()\n", "meta": {"hexsha": "f997181cf411ea08c65d06cda008a6e07629eb66", "size": 2083, "ext": "py", "lang": "Python", "max_stars_repo_path": "A2/Q1ab.py", "max_stars_repo_name": "Vasily-Piccone/ECSE543-NumericalMethods", "max_stars_repo_head_hexsha": "354119eb35f5734dcc55b9ff569eb9b7900bf56e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/Q1ab.py", "max_issues_repo_name": "Vasily-Piccone/ECSE543-NumericalMethods", "max_issues_repo_head_hexsha": "354119eb35f5734dcc55b9ff569eb9b7900bf56e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/Q1ab.py", "max_forks_repo_name": "Vasily-Piccone/ECSE543-NumericalMethods", "max_forks_repo_head_hexsha": "354119eb35f5734dcc55b9ff569eb9b7900bf56e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1475409836, "max_line_length": 114, "alphanum_fraction": 0.6077772444, "include": true, "reason": "import numpy", "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9854964211605606, "lm_q2_score": 0.9219218327098193, "lm_q1q2_score": 0.9085506667253119}} {"text": "\"\"\"\nTitle: Numerically Integrating f(x) = xe^(-ax) using the One-dimensional Trapezoidal Method\n\nSolution to Problem Set 2, Problem 1\n~ Arsh R. Nadkarni\n\nTo run:\npython trapezoidal_2_1.py\n\n\"\"\"\n# import libraries\nimport numpy as np\nfrom math import exp\nimport matplotlib.pyplot as plt\n\n# function to be integrated (integrand)\ndef f(x):\n return x*np.exp(-1*2*x)\n\n# construct the trapezoidRule function based on the pseudo-code in ProblemSet2.pdf\ndef trapezoidalRule(func,a,b,n):\n h = (b-a)/n\n I1 = func(a) + func(b)\n I2 = 0\n i = 1\n for i in range(1,n):\n x = a+i*h\n I2 += f(x)\n i += 1\n I = (h/2)*(I1+(2*I2))\n return I\n\n# function to return the value for the definite integral at n=100 (Problem 1 - Part 1)\ndef A():\n answer = trapezoidalRule(f, 0, 1, 100)\n print(\"The value of the integral computed using the Trapeizodal Rule is\", answer)\nA()\n\n# function to evaluate the error and plot the relative error as a function of n on a log-log plot, comparing it with the expected order of convergence (Problem 1 - Part 2)\ndef B():\n t = 4\n N = np.zeros(t)\n err = np.zeros(t)\n I = np.zeros(t)\n aval = 0.1484985375725405 # analytical value of the integral\n for i in range(t):\n n = 50 * (2**i) # n= 50,100,200,400\n N[i] = n\n I[i] = trapezoidalRule(f, 0, 1, n)\n err[i] = np.abs((aval-I[i])/I[i])\n fig,a = plt.subplots(figsize=(10,8))\n a.loglog(N,err,'r--',label='Relative Error',lw=3)\n a.loglog(N,1/N**2,'b-',label='Expected Convergence (1/$n^2$)',lw=3)\n a.set_xlabel('log(n)',fontweight='bold')\n a.set_ylabel('log(Relative Error)',fontweight='bold')\n plt.legend()\n plt.title('Relative Error as a function of n: log-log Plot (Case: i=1,..,n-1)', fontweight='bold')\n plt.show()\nB()\n\n# function to find an approximate n such that the numerical answer is accurate to at least five significant figures (Problem 1 - Part 3)\ndef C():\n aval = 0.1484985375725405 # analytical value of the integral (Calculated by Hand)\n eps = 1e-5 # tolerance of 5 significant figures\n n = 1\n while n < 1000:\n I = trapezoidalRule(f, 0, 1, n)\n err = abs((I-aval)/I)\n if err < eps:\n print(\"Approx. n such that numerical answer is accurate to at least 5 significant figures is\", n)\n n = 1001\n else:\n n += 1\nC()\n\n# construct the trapezoidRule function to iterate i to n instead of n-1\ndef trapezoidalRule_n(func,a,b,n):\n h = (b-a)/n\n I1 = func(a) + func(b)\n I2 = 0\n i = 1\n for i in range(0,n+1):\n x = a+i*h\n I2 += f(x)\n i += 1\n I = (h/2)*(I1+(2*I2))\n return I\n\n# function to evaluate the error and plot the relative error as a function of n on a log-log plot, comparing it with the expected order of convergence (Problem 1 - Part 2)\ndef D():\n t = 4\n N = np.zeros(t)\n err = np.zeros(t)\n I = np.zeros(t)\n aval = 0.1484985375725405 # analytical value of the integral (Calculated by Hand)\n for i in range(t):\n n = 50 * (2**i) # n= 50,100,200,400\n N[i] = n\n I[i] = trapezoidalRule_n(f, 0, 1, n)\n err[i] = np.abs((aval-I[i])/I[i])\n fig,a = plt.subplots(figsize=(10,8))\n a.loglog(N,err,'r--',label='Relative Error',lw=3)\n a.loglog(N,1/N**2,'b-',label='Expected Convergence (1/$n^2$)',lw=3)\n a.set_xlabel('log(n)',fontweight='bold')\n a.set_ylabel('log(Relative Error)',fontweight='bold')\n plt.legend()\n plt.title('Relative Error as a function of n: log-log Plot (Case: i=0,..,n) ', fontweight='bold')\n plt.show()\nD()\n\n\"\"\"\nThe order of convergence does not match the expected order (O(1/n^2)) and we obtain a slope in the plot which is equal to −1.\nThis is likely because in part D) we are iterating i from 0,..,n which means the function is integrated at both its endpoints,\nthus increasing the value of the approximation and the errors corresponding to each n.\n\n\"\"\"\n\n", "meta": {"hexsha": "23eddda80435b3b273974559591533256d31554e", "size": 3922, "ext": "py", "lang": "Python", "max_stars_repo_path": "Problem Sets/Problem Set 2/trapezoidal_2_1.py", "max_stars_repo_name": "astroarshn2000/PHYS305S20", "max_stars_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-10T06:45:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T13:50:11.000Z", "max_issues_repo_path": "Problem Sets/Problem Set 2/trapezoidal_2_1.py", "max_issues_repo_name": "astroarshn2000/PHYS305S20", "max_issues_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problem Sets/Problem Set 2/trapezoidal_2_1.py", "max_forks_repo_name": "astroarshn2000/PHYS305S20", "max_forks_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2372881356, "max_line_length": 171, "alphanum_fraction": 0.6226415094, "include": true, "reason": "import numpy", "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.9489172605148684, "lm_q1q2_score": 0.9083774252296175}} {"text": "# Cubic spline interpolation\n\nimport numpy as np\n\n\ndef spline3(x, y, X):\n '''\n Cubic Spline interpolation method.\n\n Input:\n - x : precomputed points x axis values\n - y : precomputed points y axis values\n - xq : query points x axis\n Output:\n - yq : interpolation result for query points\n '''\n (a, b, c, d) = spline3_coef(x, y)\n Y = np.zeros(len(X))\n for i in range(0, len(X)):\n Y[i] = spline3_eval(a, b, c, d, x, X[i])\n return Y\n\ndef spline3_eval(a, b, c, d, x, Xi):\n '''\n Evaluation function.\n\n Input:\n - [ a, b, c, d ] : spline coefficients list \n - x : precomputed points x axis values\n - Xi : query point\n Output:\n - Yi : spline value at query point\n '''\n i = 0\n while i < len(x)-1 and Xi > x[i+1]:\n i = i+1\n # Xi is between x[i] and x[i+1]\n Yi = a[i]*(Xi-x[i])**3 + b[i]*(Xi-x[i])**2 + c[i]*(Xi-x[i]) + d[i]\n return Yi\n\ndef build_tridiag(h, n):\n '''\n Internal helper function to build the trigiagonal matrix used to find\n the unknown values m(i)\n '''\n T = np.zeros((n,n))\n for i in range(0, n):\n T[i,i] = 2*(h[i] + h[i+1])\n for i in range(0, n-1):\n T[i+1,i] = h[i+1]\n T[i,i+1] = h[i+1]\n return T\n\ndef spline3_coef(x, y):\n '''\n Helper function returning a list of coefficients vectors.\n Assumption: x and y shall be of the same length\n\n Input:\n - x : interpolation nodes x axis values\n - y : interpolation nodes y axis values\n Output:\n - [a,b,c,d] : List of coefficients vectors\n The polynomial used in the interval [x(i), x(i+1)) is constructed as\n Ci(x) = a[i](x-x[i])^3 + b[i](x-x[i])^2 + c[i](x-x[i]) + d[i]\n '''\n n = len(x)\n # Intervals lengths\n h = x[1:n] - x[0:n-1]\n # Divided differences\n dd = (y[1:n] - y[0:n-1]) / h\n # Build the tridiagonal matrix\n T = build_tridiag(h, n-2)\n # System right hand side and solve the system\n rhs = 6*(dd[1:len(dd)] - dd[0:len(dd)-1])\n m = np.linalg.solve(T, rhs)\n # Natural boundary conditions: second derivative is zero at endpoints\n m = np.array([0] + list(m) + [0])\n # Get the coefficients\n d = y\n c = dd - h * (2*m[0:n-1] + m[1:n]) / 6\n b = m/2\n a = (m[1:n] - m[0:n-1]) / (6*h)\n return (a, b, c, d)\n", "meta": {"hexsha": "00f8034a43a5d215de0f2b3d3b6546d7899c4535", "size": 2307, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/spline3.py", "max_stars_repo_name": "davxy/numeric", "max_stars_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-03T17:02:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T04:09:34.000Z", "max_issues_repo_path": "python/spline3.py", "max_issues_repo_name": "davxy/numeric", "max_issues_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/spline3.py", "max_forks_repo_name": "davxy/numeric", "max_forks_repo_head_hexsha": "1e8b44a72e1d570433a5ba81ae0795a750ce5921", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1411764706, "max_line_length": 76, "alphanum_fraction": 0.5357607282, "include": true, "reason": "import numpy", "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307661011975, "lm_q2_score": 0.9334308068628386, "lm_q1q2_score": 0.9080702069428341}} {"text": "# %%\r\n\"\"\"In this code we wanna solve a linear equation.\"\"\"\r\nimport numpy as np\r\n# %%\r\n\"\"\"We wanna solve this system of equations:\r\n3x + y = 9\r\nx + 2y = 8\r\n\"\"\"\r\na = np.array([[3, 1], [1, 2]])\r\na\r\nb = np.array([9, 8])\r\nb\r\n# %%\r\nnp.linalg.solve(a, b)\r\n# %%\r\nb = np.array([9, 8]).reshape((-1, 1))\r\nb\r\n# %%\r\n\"\"\"The shape of output array will be the same as b.\"\"\"\r\nnp.linalg.solve(a, b)\r\n", "meta": {"hexsha": "5d660f77f8f112087802270193d32dbdd17db133", "size": 382, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy/26_SolveSystemOfLinearEquations.py", "max_stars_repo_name": "ErfanRasti/PythonCodes", "max_stars_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-01T09:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T09:59:22.000Z", "max_issues_repo_path": "NumPy/26_SolveSystemOfLinearEquations.py", "max_issues_repo_name": "ErfanRasti/PythonCodes", "max_issues_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy/26_SolveSystemOfLinearEquations.py", "max_forks_repo_name": "ErfanRasti/PythonCodes", "max_forks_repo_head_hexsha": "5e4569b760b60c9303d5cc68650a2448c9065b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1904761905, "max_line_length": 55, "alphanum_fraction": 0.5340314136, "include": true, "reason": "import numpy", "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992895791291, "lm_q2_score": 0.9381240181687351, "lm_q1q2_score": 0.9080095707226368}} {"text": "import tensorflow as tf\nimport numpy as np\n\n\"\"\"\n\nExercise 1.1: Diagonal Gaussian Likelihood\n\nWrite a function which takes in Tensorflow symbols for the means and \nlog stds of a batch of diagonal Gaussian distributions, along with a \nTensorflow placeholder for (previously-generated) samples from those \ndistributions, and returns a Tensorflow symbol for computing the log \nlikelihoods of those samples.\n\n\"\"\"\n\ndef gaussian_likelihood(x, mu, log_std):\n \"\"\"\n Args:\n x: Tensor with shape [batch, dim]\n mu: Tensor with shape [batch, dim]\n log_std: Tensor with shape [batch, dim] or [dim]\n\n Returns:\n Tensor with shape [batch]\n \"\"\"\n '''\n computation follows Docs Section \n\n https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#part-1-key-concepts-in-rl\n\n Log-Likelihood. \n \n The log-likelihood of a k -dimensional action a, for a diagonal Gaussian with mean \\mu = \\mu_{\\theta}(s) and standard deviation \\sigma = \\sigma_{\\theta}(s),\n \n is given by\n\n \\log \\pi_{\\theta}(a|s) = -\\frac{1}{2}\\left(\\sum_{i=1}^k \\left(\\frac{(a_i - \\mu_i)^2}{\\sigma_i^2} + 2 \\log \\sigma_i \\right) + k \\log 2\\pi \\right).\n '''\n # action space dimensionality\n k = x.shape.as_list()[-1]\n \n sqrd_diff_from_mean = (x - mu)**2\n weighted_sqrd_diff_from_mean = sqrd_diff_from_mean / (tf.exp(log_std)**2)\n biased_weighted_sqrd_diff_from_mean = weighted_sqrd_diff_from_mean + 2 * log_std\n log_likelihood = - 0.5 * (tf.reduce_sum(biased_weighted_sqrd_diff_from_mean, axis=1) + k * np.log(2 * np.pi))\n return log_likelihood\n\n\nif __name__ == '__main__':\n \"\"\"\n Run this file to verify your solution.\n \"\"\"\n from spinup.exercises.problem_set_1_solutions import exercise1_1_soln\n from spinup.exercises.common import print_result\n\n sess = tf.Session()\n\n dim = 10\n x = tf.placeholder(tf.float32, shape=(None, dim))\n mu = tf.placeholder(tf.float32, shape=(None, dim))\n log_std = tf.placeholder(tf.float32, shape=(dim,))\n\n your_gaussian_likelihood = gaussian_likelihood(x, mu, log_std)\n true_gaussian_likelihood = exercise1_1_soln.gaussian_likelihood(x, mu, log_std)\n\n batch_size = 32\n feed_dict = {x: np.random.rand(batch_size, dim),\n mu: np.random.rand(batch_size, dim),\n log_std: np.random.rand(dim)}\n\n your_result, true_result = sess.run([your_gaussian_likelihood, true_gaussian_likelihood],\n feed_dict=feed_dict)\n\n correct = np.allclose(your_result, true_result)\n print_result(correct)", "meta": {"hexsha": "27efc54efaef62e160fa5ed716f443c4881fecca", "size": 2568, "ext": "py", "lang": "Python", "max_stars_repo_path": "spinup/exercises/problem_set_1/exercise1_1.py", "max_stars_repo_name": "moshebeutel/spinningup", "max_stars_repo_head_hexsha": "68a1a0aa0cba47895f0b618a3660968a7c3e2a9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spinup/exercises/problem_set_1/exercise1_1.py", "max_issues_repo_name": "moshebeutel/spinningup", "max_issues_repo_head_hexsha": "68a1a0aa0cba47895f0b618a3660968a7c3e2a9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spinup/exercises/problem_set_1/exercise1_1.py", "max_forks_repo_name": "moshebeutel/spinningup", "max_forks_repo_head_hexsha": "68a1a0aa0cba47895f0b618a3660968a7c3e2a9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.24, "max_line_length": 160, "alphanum_fraction": 0.6775700935, "include": true, "reason": "import numpy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791213, "lm_q2_score": 0.936285000858894, "lm_q1q2_score": 0.9079955378157839}} {"text": "# 1. Write a NumPy program to generate five random numbers from the normal distribution.\nimport numpy as np\n\nx = np.random.normal(size=5)\nprint(x)\n# --------------------------------------------------------------------------------------------------#\n# 2. Write a NumPy program to generate six random integers between 10 and 30.\nimport numpy as np\n\nx = np.random.randint(low=10, high=30, size=6)\nprint(x)\n# --------------------------------------------------------------------------------------------------#\n# 3. Write a NumPy program to create a 3x3x3 array with random values\nimport numpy as np\n\nx = np.random.random((3, 3, 3))\nprint(x)\n# --------------------------------------------------------------------------------------------------#\n# 4. Write a NumPy program to create a 5x5 array with random values and find the minimum and maximum values.\nimport numpy as np\n\nx = np.random.random((5, 5))\nprint(\"Original Array:\")\nprint(x)\nxmin, xmax = x.min(), x.max()\nprint(\"Minimum and Maximum Values:\")\nprint(xmin, xmax)\n# --------------------------------------------------------------------------------------------------#\n# 5. Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable.\nimport numpy as np\n\nx = np.random.rand(10, 4)\nprint(\"Original array: \")\nprint(x)\ny = x[:5, :]\nprint(\"First 5 rows of the above array:\")\nprint(y)\n# --------------------------------------------------------------------------------------------------#\n# 6. Write a NumPy program to shuffle numbers between 0 and 10 (inclusive)\nimport numpy as np\n\nx = np.arange(10)\nnp.random.shuffle(x)\nprint(x)\nprint(\"Same result using permutation():\")\nprint(np.random.permutation(10))\n# --------------------------------------------------------------------------------------------------#\n# 7. Write a NumPy program to normalize a 3x3 random matrix.\nimport numpy as np\n\nx = np.random.random((3, 3))\nprint(\"Original Array:\")\nprint(x)\nxmax, xmin = x.max(), x.min()\nx = (x - xmin) / (xmax - xmin)\nprint(\"After normalization:\")\nprint(x)\n# --------------------------------------------------------------------------------------------------#\n# 8. Write a NumPy program to create a random vector of size 10 and sort it.\nimport numpy as np\n\nx = np.random.random(10)\nprint(\"Original array:\")\nprint(x)\nx.sort()\nprint(\"Sorted array:\")\nprint(x)\n# --------------------------------------------------------------------------------------------------#\n# 9. Write a NumPy program to find the nearest value from a given value in an array.\nimport numpy as np\n\nx = np.random.uniform(1, 12, 5)\nv = 4\nn = x.flat[np.abs(x - v).argmin()]\nprint(n)\n# --------------------------------------------------------------------------------------------------#\n# 10. Write a NumPy program to check two random arrays are equal or not.\nimport numpy as np\n\nx = np.random.randint(0, 2, 6)\nprint(\"First array:\")\nprint(x)\ny = np.random.randint(0, 2, 6)\nprint(\"Second array:\")\nprint(y)\nprint(\"Test above two arrays are equal or not!\")\narray_equal = np.allclose(x, y)\nprint(array_equal)\n# --------------------------------------------------------------------------------------------------#\n", "meta": {"hexsha": "a858ad69760f37aab8ba9f9970e4c837e2a4c7e2", "size": 3172, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumPy: Random Exercises & solutions.py", "max_stars_repo_name": "AmalChandru/numpy-recipes", "max_stars_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-14T14:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T03:14:20.000Z", "max_issues_repo_path": "NumPy: Random Exercises & solutions.py", "max_issues_repo_name": "AmalChandru/numpy-recipes", "max_issues_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumPy: Random Exercises & solutions.py", "max_forks_repo_name": "AmalChandru/numpy-recipes", "max_forks_repo_head_hexsha": "e80b7695e0d6fd696682027e64220c63e90c8825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2444444444, "max_line_length": 133, "alphanum_fraction": 0.4820302648, "include": true, "reason": "import numpy", "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.9465966698235384, "lm_q1q2_score": 0.9079322489561752}} {"text": "from scipy.stats import norm\nimport numpy as np\nfrom scipy import special\nfrom scipy import integrate\n\ndef integrate_normal(x1, x2, mu, sigma):\n sup = 0.5*((special.erf((x2-mu)/(sigma*np.sqrt(2))))-(special.erf((x1-mu)/(sigma*np.sqrt(2)))))\n return sup\n \nmy_mu = 0\nmy_sigma = 1\n\nmy_x1 = 0\nmy_x2 = my_sigma\n\n# The expected value is equal to 0.3413...\nmy_sup = integrate_normal(x1= my_x1, x2= my_x2, mu = my_mu, sigma = my_sigma)\n\nx = np.arange(my_x1, my_x2, 0.0001)\ny = norm.pdf(x, loc=my_mu, scale= my_sigma) # normal_pdf(x, mean = my_mu, std = my_sigma)\n\nsup_trapz = integrate.trapz(y,x)\nsup_simps = integrate.simps(y,x)\n\nprint(\"Solution Using erf: {:.9f}\".format(my_sup))\nprint(\"Using the trapezoidal rule, trapz: {:.10f}\".format(sup_trapz))\nprint(\"Using the composite Simpson rule, simps: {:.10f}\".format(sup_simps))\n\n'''\nOutput:\nSolution Using erf: 0.341344746\nUsing the trapezoidal rule, trapz: 0.3413205476\nUsing the composite Simpson rule, simps: 0.3413205478\n'''", "meta": {"hexsha": "94b9b592fc4dba0fb02311bd5758a65f721b71d4", "size": 981, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/chapter_09/listing_09_02.py", "max_stars_repo_name": "guinslym/python_earth_science_book", "max_stars_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2021-04-19T10:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:34:47.000Z", "max_issues_repo_path": "code/chapter_09/listing_09_02.py", "max_issues_repo_name": "guinslym/python_earth_science_book", "max_issues_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/chapter_09/listing_09_02.py", "max_forks_repo_name": "guinslym/python_earth_science_book", "max_forks_repo_head_hexsha": "f4dd0115dbbce140c6713989f630a71238daa72c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:06:19.000Z", "avg_line_length": 28.8529411765, "max_line_length": 99, "alphanum_fraction": 0.7064220183, "include": true, "reason": "import numpy,from scipy", "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357561234475, "lm_q2_score": 0.9273632896242074, "lm_q1q2_score": 0.9079218194583636}} {"text": "from sympy.abc import x\nimport sympy as sp\nimport math\n\n\ndef newton_iteration(x0, func, tol=1e-9, Max_iter=100):\n \"\"\" Solve non-linear equation by Newton iteratin method.\n\n Args:\n x0: double, the initial value of the iteration\n func: symbol object, the non-linear equation to be solved\n tol: double, the iteration accuracy\n Max_iter: int, maximum iteration number\n\n Returns:\n k: int, iteration number\n v: double, root of the non-linear equation\n \"\"\"\n # derivative\n y_diff = sp.diff(func(x))\n\n # first iteration\n k = 1\n u = x0\n v = u - func(u)/y_diff.subs(x, u)\n\n # iteration\n while math.fabs(v - u) >= tol and y_diff.subs(x, v) != 0 and k < Max_iter:\n k += 1\n u = v\n v = u - func(u)/y_diff.subs(x, u)\n\n return k, v \n\n\ndef f(x):\n return sp.Pow(x, 3) + sp.Pow(x, 2) - 3*x - 3\n\n\nif __name__ == '__main__':\n \"\"\" The initial values\n When x0 = -2, it converges to another root -sqrt{3}\n When x0 = -1, it is the root of the function\n When x0 = 0, it converges to -1\n When x0 = 2, it converges to sqrt{3} quickly\n When x0 = 3000000, it converges to sqrt{3} slowly\n \"\"\"\n x0_lst = [-2.0, -1.0, 0.0, 2.0, 9999999999999999.0]\n for x0 in x0_lst:\n n, root = newton_iteration(x0, f, 1e-6)\n print(f\"The root of the non-linear equation with initial value {x0} is {root:.7f}.\")\n print(f\"Iteration number is {n}.\")\n\n", "meta": {"hexsha": "c09971426b117b376ef588ad2987f02efdd99a4b", "size": 1450, "ext": "py", "lang": "Python", "max_stars_repo_path": "NonLinearEquation/newton_iteration.py", "max_stars_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_stars_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NonLinearEquation/newton_iteration.py", "max_issues_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_issues_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NonLinearEquation/newton_iteration.py", "max_forks_repo_name": "KristopherTsui/NumericalAnalysisExperiment", "max_forks_repo_head_hexsha": "c751c2c4f94c0943f1b00b5fb52f56e7ba240bbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8518518519, "max_line_length": 92, "alphanum_fraction": 0.595862069, "include": true, "reason": "import sympy,from sympy", "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060719, "lm_q2_score": 0.9399133531922388, "lm_q1q2_score": 0.9078619067930627}} {"text": "from sympy import Matrix\nfrom pprint import pprint\n\n\"\"\"\n Vedant Raghuwanshi(118EE0705)\n EE3302 Advanced Control System Project: Algorithm to find if the i/p matrix is nilpotent or not.\n Principle:\n A matrix is nilpotent iff:\n 1. The matrix is square and all the eigenvalues are 0.\n or\n 2. A square matrix A such that A^n is the zero matrix 0 for some positive \n integer matrix power n, known as the index. \n\"\"\"\n\n\ndef check_nilpotency(matrix):\n sp_matrix = Matrix(matrix)\n eigenvalues = sp_matrix.eigenvals() # finding eigenvalues of the input matrix\n\n # eigenvalues is dictionary with eigen values of the matrix as keys and their multiplicity as dictionary values.\n\n for x in eigenvalues.keys():\n if (\n x != 0\n ): # if any value other than 0 is present in keys then matrix is NOT nilpotent\n return eigenvalues, False\n\n return eigenvalues, True # matrix is nilpotent\n\n\nif __name__ == \"__main__\":\n\n size = int(input(\"Enter Matrix Size: \"))\n matrix = []\n for i in range(size):\n row = list(map(complex, input().split()))\n matrix.append(row)\n\n print(\"Your input matrix is:\")\n print(matrix)\n print()\n eigvalues, isnilp = check_nilpotency(matrix)\n print(f\"The matrix is nilpotent: {isnilp}\")\n print()\n print(\"The eigen values of the matrix and their corresponding multiplicity are: \\n\")\n pprint(eigvalues)\n", "meta": {"hexsha": "bafea74a7cf9a49be53fb718beeed6ebeafa00fb", "size": 1484, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/algorithm.py", "max_stars_repo_name": "007vedant/Nilpotent_GUI", "max_stars_repo_head_hexsha": "694ee56a442181e630fe9a711fe429109a788864", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithm.py", "max_issues_repo_name": "007vedant/Nilpotent_GUI", "max_issues_repo_head_hexsha": "694ee56a442181e630fe9a711fe429109a788864", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm.py", "max_forks_repo_name": "007vedant/Nilpotent_GUI", "max_forks_repo_head_hexsha": "694ee56a442181e630fe9a711fe429109a788864", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5744680851, "max_line_length": 116, "alphanum_fraction": 0.6462264151, "include": true, "reason": "from sympy", "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138118632621, "lm_q2_score": 0.9284087936225136, "lm_q1q2_score": 0.9077181005800404}} {"text": "import numpy as np\r\n\r\n# MATRIX ADDITION\r\n# dim of two matrices must match \r\n\r\nnp.random.seed(0)\r\n\r\nmatrix1 = np.random.randint(1,100,(5,4))\r\n\r\nmatrix2 = np.random.randint(1,100,(5,4))\r\n\r\nmatrix1 + matrix2\r\n\r\n# what happens when matrix dim doesn't match !!\r\n\r\nmatrix3 = np.arange(1,3)\r\n\r\nmatrix2 + matrix3\r\n\r\n# ValueError: operands could not be broadcast together with shapes (5,4) (2,)\r\n\r\n# MATRIX SUBTRACTION\r\n\r\nmatrix1 - matrix2\r\n\r\n# MATRIX DIVISION\r\n\r\nmatrix1/matrix2\r\n\r\n# MATRIX MULTIPLICATION\r\n\r\n# 1. hadamard product\r\n# 2. dot or matrix matrix product\r\n\r\n# 1. hadamard product --> element or position wise multiplication\r\n\r\nhadamard_matrix1 = np.random.randint(1,10,(2,2))\r\nhadamard_matrix2 = np.random.randint(1,10,(2,2))\r\n\r\nhadamard_matrix1 * hadamard_matrix2\r\n\r\n# 2. dot or matrix matrix product --> multiply 1st row with 1st column, 1st row with 2nd column and so on\r\n\r\ndot_matrix1 = np.random.randint(1,10,(2,2))\r\ndot_matrix2 = np.random.randint(1,10,(2,2))\r\n\r\nnp.matmul(dot_matrix1,dot_matrix2)\r\n\r\n# alternate to matmul is \"@\" and \"dot\" function\r\n\r\ndot_matrix1 @ dot_matrix2\r\n\r\ndot_matrix1.dot(dot_matrix2)\r\n\r\n# MATRIX VECTOR MULTIPLICATION --> important for machine learning\r\n\r\n'''\r\nhow ?\r\n\r\ndataset is divided into independent and dependent features\r\n\r\nsuppose independent feature set is 4 X 3 --> X\r\nsuppose dependent feature set is 4 X 1 --> y\r\n\r\nmultiplication is not possible between two matrices as number of columns in \r\nindependent feature does not match the rows in dependent feature\r\n\r\nin order to get the dependent feature, have to multiple with unknown vector (W, weight vector) to get\r\ndependent feature\r\n\r\nNOTE: is the core logic of ML algorithms\r\n\r\n'''\r\n\r\nmatrix1 = np.random.randint(10,100,(4,4)) # X\r\n\r\nmatrix2 = np.arange(2,6) # y\r\n\r\noutput_vector = matrix1.dot(matrix2) # W\r\n\r\n# MATRIX SCALAR MULTIPLICATION\r\n\r\n2 * matrix1\r\n", "meta": {"hexsha": "d797f98c0961e33a29ceca50280ea7b5c124cba1", "size": 1856, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix/matrix_arithmetic_operations.py", "max_stars_repo_name": "Akshaykumarcp/linear_algebra", "max_stars_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-06T12:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:31:53.000Z", "max_issues_repo_path": "matrix/matrix_arithmetic_operations.py", "max_issues_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_issues_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix/matrix_arithmetic_operations.py", "max_forks_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_forks_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0952380952, "max_line_length": 106, "alphanum_fraction": 0.7106681034, "include": true, "reason": "import numpy", "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211590308922, "lm_q2_score": 0.930458262243501, "lm_q1q2_score": 0.9070304016300795}} {"text": "'''\n Newton's Method\n Purpose:\n Computes approximate solution of f(x) = 0 by Newton's method\n Input: \n f: function handle\n f_der: the derivative of function f\n x0: initial guess\n tol: tolerance error\n iters: iteration number\n max_iters: maximum iteration number\n Output: \n Approximate solution \n\nLast edited by Xiaozhou Li, September 23, 2020\n'''\n\nimport numpy as np\n\ndef newton_iters(f, f_der, x0, iters):\n x = np.zeros(iters+1)\n x[0] = x0\n for i in range(iters):\n x[i+1] = x[i] - f(x[i])/f_der(x[i])\n return x\n\ndef newton_tol(f, f_der, x0, tol, max_iters=100):\n x_old = x0\n x_new = x_old - f(x_old)/f_der(x_old)\n iters = 1\n while (np.abs(x_new - x_old) > tol):\n x_old = x_new\n x_new = x_old - f(x_old)/f_der(x_old)\n iters += 1\n if (iters > 100):\n print (\"Maximum iteration number achieved!\")\n return\n return x_new\n\n#########################################################\n# Example\ndef f(x):\n return x**3 + 10*x - 20\n \ndef f_der(x):\n return 3*x**2 + 10\n\nprint (newton_tol(f, f_der, 1.5, 1.e-12))\nprint (newton_iters(f, f_der, 1.5, 20))\n", "meta": {"hexsha": "5c67d911e0052a1d0baacb9639e716869a290e0f", "size": 1200, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/newton.py", "max_stars_repo_name": "xiaozhouli/numerical_analysis", "max_stars_repo_head_hexsha": "68600ca56f8fdec6a2d22c65ec02ec2871546ea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-06T02:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T02:11:33.000Z", "max_issues_repo_path": "Code/newton.py", "max_issues_repo_name": "xiaozhouli/numerical_analysis", "max_issues_repo_head_hexsha": "68600ca56f8fdec6a2d22c65ec02ec2871546ea2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/newton.py", "max_forks_repo_name": "xiaozhouli/numerical_analysis", "max_forks_repo_head_hexsha": "68600ca56f8fdec6a2d22c65ec02ec2871546ea2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 68, "alphanum_fraction": 0.55, "include": true, "reason": "import numpy", "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.9390248255340266, "lm_q1q2_score": 0.9070036773853625}} {"text": "import scipy.stats as st\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-5,10,200) #200 points distrubuted between -5 and 10\nks = np.arange(50) #from 0-49\n\n#DISCRETE PMF\nplt.title(\"DISCRETE PMF\")\npmf_binomial = st.binom.pmf(ks,50,0.25) #0.25 = successful chance, 50 = event\nplt.bar(ks,pmf_binomial,label=\"Binomial Example (Dice)\",alpha=0.8)\n\n\n#Poisson Dist. - change the parameters according to formulae\npmf_poisson = st.poisson.pmf(ks,30) #same as bino because they're discrete\n#30 = characteristic rate\nplt.bar(ks,pmf_poisson,label=\"Poisson Example (car crash)\",alpha=0.8)\nplt.legend()\n\nprint(\"Binomial Dist for chance of rolling 1 10 times\")\nprint(st.binom.pmf(10,50,0.25)) #chances of rolling 10 \"1's\" on a default\nprint(\"Poisson Dist for chance of getting 50 crashes\")\nprint(st.poisson.pmf(50,30)) #what is the chance that we get 50 crashes\n\nplt.show()\n\n\n#CONTINUOUS PDF/PMF\n\n#Uniform, normal, exponential, student-t, log-normal, skew-normal\nplt.title(\"CONTINUOUS PDF\")\n\npdf_uniform = st.uniform.pdf(x,-4,10) #parameterized by low and up bound\nplt.plot(x,pdf_uniform,label=\"Uniform (-4,6)\")\n\npdf_normal = st.norm.pdf(x,5,2) #parameterized by location and scalerespectively\nplt.plot(x,pdf_normal,label=\"Normal (5,2)\")\n\npdf_exponential = st.expon.pdf(x,loc=-2,scale=2) #characteristic rate = scale(1)\nplt.plot(x,pdf_exponential,label=\"Exponential(0.5)\")\n\npdf_studentt = st.t.pdf(x,1)# parameterized by degree of freedom\n# dof = no of datapoints - 1\nplt.plot(x,pdf_studentt,label=\"Student-t\")\n\npdf_lognorm = st.lognorm.pdf(x,1)#parameterized by scale parameter\nplt.plot(x,pdf_lognorm,label=\"Lognorm(1)\")\n\npdf_skewnorm = st.skewnorm.pdf(x,-6) #default instead of -6 is 0 (alpha param)\nplt.plot(x,pdf_skewnorm,label=\"Skewnorm(-6)\")\n\nplt.legend()\nplt.xlabel(\"x\")\nplt.ylabel(\"Probability\")\nplt.show()\n\n# loc and scale(alpha) can be used anywhere as it's mu and sigma. It doesn't\n# change anything as it is linear transformation of input vector, eg below\n# loc and scale are convinient linear transformation as you can change data\nplt.plot(x,st.t.pdf(x,1,loc=4,scale=2),label=\"In built\")\nplt.plot(x,st.t.pdf((x-4)/2,1,loc=0,scale=1),label=\"Manually\")\n\nplt.legend()\nplt.show()\n", "meta": {"hexsha": "f9912518a3fb1bb45227e91b8c2c3190bce3e5dd", "size": 2196, "ext": "py", "lang": "Python", "max_stars_repo_path": "Probability_pdf.py", "max_stars_repo_name": "WestHamster/Feature_engg", "max_stars_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Probability_pdf.py", "max_issues_repo_name": "WestHamster/Feature_engg", "max_issues_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Probability_pdf.py", "max_forks_repo_name": "WestHamster/Feature_engg", "max_forks_repo_head_hexsha": "18d2e935db14cb68c734fb67e99fe427841d1d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7846153846, "max_line_length": 80, "alphanum_fraction": 0.7399817851, "include": true, "reason": "import numpy,import scipy", "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9825575147530352, "lm_q2_score": 0.9230391680088872, "lm_q1q2_score": 0.9069390709385216}} {"text": "from numpy import zeros\n\nX = [0.0, 1.5, 2.8, 4.4, 6.1, 8.0]\nY = [0.0, 0.9, 2.5, 6.6, 7.7, 8.0]\n\nn = len(X)-1 # Degree of polynomial = number of points - 1\n\nprint(\"X =\", X)\nprint(\"Y =\", Y, end='\\n\\n')\n\nxp = float(input(\"Find Y for X = \"))\n\n\n## y(x) = a0 + (x-x1)a1 + (x-x1)(x-x2)a2 + ... + (x-x1)(x-x2)...(x-xn)an\n\n## Divided differences procedure to get the a's for n+1 = 4 data points:\n\n## Col: 1 2 3 4\n## x1 y11 = Y1 a0 = y11\n## x2 y21 = Y2 y22 a1 = y22\n## x3 y31 = Y3 y32 y33 a2 = y33\n## x4 y41 = Y4 y42 y43 y44 a3 = y44 an = y[n+1][n+1]\n\n## yi2 = (yi1 - y11) / (xi - x1) where i = 2,3,4\n## yi3 = (yi2 - y22) / (xi - x2) where i = 3,4\n## yi4 = (yi3 - y33) / (xi - x3) where i = 4\n## yi(j+1) = (yij - yjj) / (xi - xj) where j = 1 to n; i = j+1 to n+1\n\n\nDy = zeros((n+1, n+1)) # Dy[6,6] # Dy[0-5, 0-5] # Index stars from 0\nDy[:,0] = Y # y11 = Y1, y21 = Y2, y(n+1)1 = Y(n+1) # Dy[i][0] = Y[i]\n\nfor j in range(n):\n for i in range(j+1, n+1):\n Dy[i, j+1] = (Dy[i,j] - Dy[j,j]) / (X[i] - X[j])\n\n\n## Substitution procedure:\n## y(x) = y11 + (x-x1)y22 + (x-x1)(x-x2)y33+...+(x-x1)(x-x2)...(x-xn)y[n+1][n+1]\n\n## Index starts from 0\n##Dy(x) = y00 + (x-x0)y11 + (x-x0)(x-x1)y22+...+(x-x0)(x-x1)...(x-x[n-1])ynn\n##Dy(x) = y00 + sum( prod(x-xj) * y[i+1][i+1] ) where i= 0 to n-1; j= 0 to i\n\n\nyp = Dy[0,0] # Initial summation value, a0, y00\nfor i in range(n):\n \n xprod = 1 # Initial product value\n for j in range(i+1):\n xprod *= xp - X[j] # x[0] to x[i] where i = 0 to n-1\n\n yp += xprod * Dy[i+1][i+1] # Dy[1,1] to D[n,n]\n\n## yp += prod(xp - X[:i+1]) * Dy[i+1][i+1]\n\n\nprint(\"The Y = %.1f\"% yp)\n", "meta": {"hexsha": "34957046172c9abfd8e4ece396661e7085ab5909", "size": 1804, "ext": "py", "lang": "Python", "max_stars_repo_path": "2. Interpolation and Curve Fitting/3. Newton's Interpolation Method.py", "max_stars_repo_name": "dmNadim/Numerical-Methods", "max_stars_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2. Interpolation and Curve Fitting/3. Newton's Interpolation Method.py", "max_issues_repo_name": "dmNadim/Numerical-Methods", "max_issues_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2. Interpolation and Curve Fitting/3. Newton's Interpolation Method.py", "max_forks_repo_name": "dmNadim/Numerical-Methods", "max_forks_repo_head_hexsha": "2c74312ea4efddd7db65483fef02fea710963dcf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5762711864, "max_line_length": 80, "alphanum_fraction": 0.4373614191, "include": true, "reason": "from numpy", "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551566309689, "lm_q2_score": 0.9399133552961427, "lm_q1q2_score": 0.9068802476437993}} {"text": "# Solve the roots of the quadratic equation 1: x^2 - 2x - 8 = 0 \n# -----------------------------------------------------------------\n# a = 1\n# b = -2\n# c = -8\n\n# r1 = (-b + (b**2-4*a*c)**0.5)/(2*a)\n# r2 = (-b - (b**2-4*a*c)**0.5)/(2*a)\n\n# print(\"r1 = %6.4f, r2 = %6.4f\" %(r1, r2))\n# -----------------------------------------------------------------\n\n# Solve the roots of the quadratic equation 2: x^2 - 2x - 8 = 0 \n# -----------------------------------------------------------------\n# from sympy import *\n\n# x = Symbol('x');\n# f = Symbol('f');\n# f = x**2 - 2*x -8\n# root = solve(f)\n# print(root)\n# -----------------------------------------------------------------\n\n# Draw a quadratic equation in one variable 1: y = 3x^2 -12x +10\n# -----------------------------------------------------------------\n# import matplotlib.pyplot as plt\n# import numpy as np\n\n# def f(x):\n# return (3*x**2 - 12*x + 10)\n\n# a = 3\n# b = -12\n# c = 10\n\n# r1 = (-b + (b**2-4*a*c)**0.5)/(2*a)\n# r2 = (-b - (b**2-4*a*c)**0.5)/(2*a)\n# r1_y = f(r1)\n# r2_y = f(r2)\n# print('root1 = ', r1)\n# print('root2 = ', r2)\n\n# x = np.linspace(0, 4, 100)\n# y = 3*x**2 - 12*x + 10\n# plt.plot(x, y)\n\n# plt.plot(r1, r1_y, '-o')\n# plt.text(r1-0.3, r1_y+0.3, '('+str(round(r1,2))+','+str(0)+')')\n# plt.plot(r2, r2_y, '-o')\n# plt.text(r2-0.3, r2_y+0.3, '('+str(round(r2,2))+','+str(0)+')')\n\n# plt.show()\n# -----------------------------------------------------------------\n\n# Draw a quadratic equation in one variable 2: y = -3x^2 +12x -9\n# -----------------------------------------------------------------\n# import matplotlib.pyplot as plt\n# import numpy as np\n\n# def f(x):\n# return (-3*x**2 + 12*x - 9)\n\n# a = -3\n# b = 12\n# c = -9\n\n# r1 = (-b + (b**2-4*a*c)**0.5)/(2*a)\n# r2 = (-b - (b**2-4*a*c)**0.5)/(2*a)\n# r1_y = f(r1)\n# r2_y = f(r2)\n# print('root1 = ', r1)\n# print('root2 = ', r2)\n\n# x = np.linspace(0, 4, 100)\n# y = -3*x**2 + 12*x - 9\n# plt.plot(x, y)\n\n# plt.plot(r1, r1_y, '-o')\n# plt.text(r1-0.3, r1_y+0.3, '('+str(round(r1,2))+','+str(0)+')')\n# plt.plot(r2, r2_y, '-o')\n# plt.text(r2-0.3, r2_y+0.3, '('+str(round(r2,2))+','+str(0)+')')\n\n# plt.show()\n# -----------------------------------------------------------------\n\n# The minimum and maximum values ​​of a quadratic equation in one variable: 3x^2 -12x +10\n# -----------------------------------------------------------------\n# import matplotlib.pyplot as plt\n# from scipy.optimize import minimize_scalar\n# import numpy as np\n\n# def f(x):\n# return (3*x**2 - 12*x + 10)\n\n# a = 3\n# b = -12\n# c = 10\n\n# r = minimize_scalar(f, bounds=(0, 4), method='bounded')\n# print(\"when x is %4.2f, minimize is %4.2f\" %(r.x, f(r.x)))\n# r1 = (-b + (b**2-4*a*c)**0.5)/(2*a)\n# r2 = (-b - (b**2-4*a*c)**0.5)/(2*a)\n# r1_y = f(r1)\n# r2_y = f(r2)\n# print('root1 = ', r1)\n# print('root2 = ', r2)\n\n# x = np.linspace(0, 4, 100)\n# y = 3*x**2 - 12*x + 10\n# plt.plot(x, y)\n\n# plt.plot(r.x, f(r.x), '-o')\n# plt.text(r.x-0.3, f(r.x)+0.3, '('+str(round(r.x,2))+','+str(round(f(r.x),2))+')')\n# plt.plot(r1, r1_y, '-o')\n# plt.text(r1-0.3, r1_y+0.3, '('+str(round(r1,2))+','+str(0)+')')\n# plt.plot(r2, r2_y, '-o')\n# plt.text(r2-0.3, r2_y+0.3, '('+str(round(r2,2))+','+str(0)+')')\n\n# plt.show()\n# -----------------------------------------------------------------\n\n\n# The minimum and maximum values ​​of a quadratic equation in one variable: -3x^2 + 12x -9\n# -----------------------------------------------------------------\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize_scalar\nimport numpy as np\n\ndef fmax(x):\n return (-3*x**2 + 12*x - 9)*(-1)\n\ndef f(x):\n return (-3*x**2 + 12*x - 9)\n\na = -3\nb = 12\nc = -9\n\nr = minimize_scalar(fmax, bounds=(0, 4), method='bounded')\nprint(\"when x is %4.2f, minimize is %4.2f\" %(r.x, f(r.x)))\nr1 = (-b + (b**2-4*a*c)**0.5)/(2*a)\nr2 = (-b - (b**2-4*a*c)**0.5)/(2*a)\nr1_y = f(r1)\nr2_y = f(r2)\nprint('root1 = ', r1)\nprint('root2 = ', r2)\n\nx = np.linspace(0, 4, 100)\ny = -3*x**2 + 12*x - 9\nplt.plot(x, y)\n\nplt.plot(r.x, f(r.x), '-o')\nplt.text(r.x-0.3, f(r.x)+0.3, '('+str(round(r.x,2))+','+str(round(f(r.x),2))+')')\nplt.plot(r1, r1_y, '-o')\nplt.text(r1-0.3, r1_y+0.3, '('+str(round(r1,2))+','+str(0)+')')\nplt.plot(r2, r2_y, '-o')\nplt.text(r2-0.3, r2_y+0.3, '('+str(round(r2,2))+','+str(0)+')')\n\nplt.show()\n# -----------------------------------------------------------------\n", "meta": {"hexsha": "3539b27b9c1bba7b3e6ea9243dfb3292488cd889", "size": 4314, "ext": "py", "lang": "Python", "max_stars_repo_path": "Python3/Py_0004 Quadratic Function.py", "max_stars_repo_name": "JingHengLin/codeEveryday", "max_stars_repo_head_hexsha": "a7359d1c445cca85b80f47ef290564f959af46e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python3/Py_0004 Quadratic Function.py", "max_issues_repo_name": "JingHengLin/codeEveryday", "max_issues_repo_head_hexsha": "a7359d1c445cca85b80f47ef290564f959af46e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python3/Py_0004 Quadratic Function.py", "max_forks_repo_name": "JingHengLin/codeEveryday", "max_forks_repo_head_hexsha": "a7359d1c445cca85b80f47ef290564f959af46e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7950310559, "max_line_length": 90, "alphanum_fraction": 0.4191006027, "include": true, "reason": "import numpy,from scipy,from sympy", "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9799765628041175, "lm_q2_score": 0.925229962761739, "lm_q1q2_score": 0.9067036787106306}} {"text": "### import libraries ###\n'''\nNOTES:\nThe Fourier transform can be obtained from the complex notation Fourier series\nSo imaginary components correspond to sines and real components correspond to cosines\n'''\nimport numpy as np\nfrom mpmath import *\nimport matplotlib.pyplot as plt\n### make MATLAB-like commands for use in Python ###\nfft, fftshift, ifft = np.fft.fft, np.fft.fftshift, np.fft.ifft\nabs, rndm, exp = np.abs, np.random.normal, np.exp\ndef sech(x) : return 1/np.cosh(x)\nnp.set_printoptions(precision=3)\n\nn,m,pi = 32,3,np.pi\nL = pi\nt2 = np.linspace(-L,L,n+1).astype('float')\nt = t2[0:n] \nk = (2*pi/(2*L)) * np.append(np.arange(0,n/2),np.arange(-n/2,0))\nks = fftshift(k)\nCos = np.cos(t*m)\nSin = np.sin(t*m)\nFtCos = fft(Cos) \nFtSin = fft(Sin) \n\n''' MATLAB (same as above)\nL=pi; \nn=8;\nm=3;\nt2=linspace(-L,L,n+1);\nt=t2(1:n);\nk=(2*pi/(2*L))*[0:(n/2-1) -n/2:-1];\nks = fftshift(k);\nCos=cos(m*t);\nSin=sin(m*t);\nFtCos = fft(Cos);\nFtSin = fft(Sin);\nplot(ks,fftshift(FtCos), ks,fftshift(abs(FtCos)), ks,fftshift(imag(FtCos)) );\nplot(ks,fftshift(FtSin), ks,fftshift(abs(FtSin)), ks,fftshift(imag(FtSin)) );\nxlabel(\"ks\")\n'''\n\nf, (ax1, ax2) = plt.subplots(2, 1)\nplt.title('$FT(\\cos(%dt)), t \\in [-\\pi,\\pi]$' % (m))\nax1.plot(t, Cos, label='$\\cos(%dt)$' % (m))\nax1.axvline(x=2*L/m)\nax2.plot(fftshift(k), fftshift(abs(FtCos)), label='abs')\nax2.plot(fftshift(k), fftshift(np.real(FtCos)), label='real')\nax2.plot(fftshift(k), fftshift(np.imag(FtCos)), label='imaginary')\nplt.legend()\nplt.show()\n\nf, (ax1, ax2) = plt.subplots(2, 1)\nplt.title('$FT(\\sin(%dt)), t \\in [-\\pi,\\pi]$' % (m))\nax1.plot(t, Cos, label='$\\sin(%dt)$' % (m))\nax2.plot(fftshift(k), fftshift(abs(FtSin)), label='abs')\nax2.plot(fftshift(k), fftshift(np.real(FtSin)), label='real')\nax2.plot(fftshift(k), fftshift(np.imag(FtSin)), label='imaginary')\nplt.legend()\nplt.show()\n\n'''\nk\nks\nCos\nFtCos\n'''\nprint(\"\\nt\",t)\nprint(\"\\nk\",k)\nprint(\"\\nks\",ks)\nprint(\"\\nCos\",Cos)\nprint(\"\\nFtCos\",FtCos)", "meta": {"hexsha": "2a1b3e957cdda9460a948091675ef8466f558363", "size": 1939, "ext": "py", "lang": "Python", "max_stars_repo_path": "DFT_and_Fourier_series/pythonExample_SingleFreq1D.py", "max_stars_repo_name": "aruymgaart/AMATH", "max_stars_repo_head_hexsha": "87579a076ec74094d0420c2a1f477022aaefb6bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DFT_and_Fourier_series/pythonExample_SingleFreq1D.py", "max_issues_repo_name": "aruymgaart/AMATH", "max_issues_repo_head_hexsha": "87579a076ec74094d0420c2a1f477022aaefb6bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DFT_and_Fourier_series/pythonExample_SingleFreq1D.py", "max_forks_repo_name": "aruymgaart/AMATH", "max_forks_repo_head_hexsha": "87579a076ec74094d0420c2a1f477022aaefb6bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5616438356, "max_line_length": 85, "alphanum_fraction": 0.6451779268, "include": true, "reason": "import numpy,from mpmath", "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.97997655637136, "lm_q2_score": 0.925229951422338, "lm_q1q2_score": 0.9067036616465035}} {"text": "import math\nimport matplotlib.pyplot as plt\nimport scipy.optimize as op\nimport numpy as np\nnp.set_printoptions(suppress=True)\n\ndef plot_cost_history(cost_history):\n\tplt.clf()\n\tplt.title('Cost J x iterations')\n\t\n\tplt.ylabel('Cost J')\n\tplt.xlabel('Number of iterations')\n\n\tplt.plot(cost_history, 'g.')\n\t\n\tplt.show()\n\t\n# 1.2.1 Warmup exercise: sigmoid function\ndef sigmoid(z):\n\tif np.isscalar(z):\n\t\treturn 1 / (1 + math.e ** (-z))\n\telse:\n\t\treturn np.ones(z.size) / (np.ones(z.size) + np.repeat(np.e, z.size) ** (-z))\n\t\t\ndef hypothesis(theta, X):\n\treturn sigmoid(np.dot(X, theta))\n\n# 1.2.2 Cost function and gradient\ndef compute_cost(theta, X, y):\n\tm = X.shape[0]\n\t\n\th = hypothesis(theta, X)\n\terror = np.sum(-y * np.log(h) - (1 - y) * np.log(1 - h))\n\n\treturn error / m\n\t\n# 1.2.3 Learning parameters using fminunc\ndef gradient(theta, X, y):\n\tm = X.shape[0]\n\t\n\th = hypothesis(theta, X)\n\t\n\tfor j in range(theta.shape[0]):\n\t\ttheta[j] = np.sum((h - y) * X[:, j]) / m\n\t\t\t\n\treturn theta\n\t\nif __name__ == '__main__':\n\t# Import data\n\tdata = np.loadtxt(\"ex2data1.txt\", delimiter=\",\")\n\n\tpositive = data[data[:,2] == 1][:,0:2]\n\tnegative = data[data[:,2] == 0][:,0:2]\n\n\t# 1.1 Visualizing the data\n\tplt.ylabel('Exame 2 score')\n\tplt.xlabel('Exam 1 score')\n\n\tplt.plot(positive[:,0], positive[:,1], 'b+', label = 'Admitted')\n\tplt.plot(negative[:,0], negative[:,1], 'rx', label = 'Not admitted')\n\n\tplt.legend()\n\tplt.show()\n\n\t# 1.2 Implementation\n\t\t\n\t# For large positive values of x, the sigmoid should be close to 1, \n\t# while for large negative values, the sigmoid should be close to 0. \n\t# Evaluating sigmoid(0) should give you exactly 0.5.\n\tassert sigmoid(0) == 0.5\n\tassert sigmoid(129378) == 1\n\tassert round(sigmoid(-111)) == 0\n\n\t# For a matrix, your function should perform the sigmoid function on every element.\n\tassert np.all(sigmoid(np.array([0,0])) == 0.5)\n\n\ttheta = np.zeros(3)\n\n\t# Evaluation\n\t## Create the bias column, set to 1\n\tX = data[:, 0:2]\n\tX = np.stack((np.ones(data.shape[0]), X[:, 0], X[:, 1]), axis=-1)\n\n\ty = data[:, 2]\n\n\t# You should see that the cost is about 0.693.\n\tassert round(compute_cost(theta, X, y), 3) == 0.693\n\n\tresult = op.minimize(compute_cost, theta, (X, y), 'TNC', gradient, options = {'maxiter': 400})\n\ttheta = result.x\n\tcost = result.fun\n\n\ttry:\n\t\t# You should see that the cost is about 0.203.\n\t\tassert(round(cost, 3) == 0.203)\n\n\t\t# 1.2.4 Evaluating logistic regression\n\t\t# You should expect to see an admission probability of 0.776\n\t\tassert(round(hypothesis(theta, np.array([1, 45, 85])), 3) == 0.776)\n\t\t\n\t# There is no fminunc in scipy, so I have used https://en.wikipedia.org/wiki/Truncated_Newton_method.\n\t# However, it does not produce correct theta values, which therefore yelds terrible prediction.\n\t# In this case, I went back to gradient descent with manually tuned alpha and iterations.\n\texcept:\n\t\ttheta = np.zeros(3)\n\t\talpha = 0.00417\n\t\titerations = 400000\n\t\tcost_history = []\n\n\t\tm = X.shape[0]\n\t\t\n\t\tfor i in range(iterations):\n\t\t\th = hypothesis(theta, X)\n\t\t\t\n\t\t\tfor j in range(theta.shape[0]):\n\t\t\t\ttheta[j] = theta[j] - alpha * np.sum((h - y) * X[:, j]) / m\n\t\t\t\t\n\t\t\tcost_history.append(compute_cost(theta, X, y))\n\n\t\tcost = compute_cost(theta, X, y)\n\n\t\t# You should see that the cost is about 0.203.\n\t\tassert(round(cost, 3) == 0.203)\n\n\t\t# 1.2.4 Evaluating logistic regression\n\t\t# You should expect to see an admission probability of 0.776\n\t\tassert(round(hypothesis(theta, np.array([1, 45, 85])), 3) == 0.776)\n\t\t\n\t\tplot_cost_history(cost_history)\n\t\t\n\t# The predict function will produce “1” or “0” predictions given a dataset \n\t# and a learned parameter vector θ.\n\tprint('Train Accuracy: ', np.mean((hypothesis(theta, X) >= 0.5).astype(float) == y) * 100)\n", "meta": {"hexsha": "1553bf809f5aa3250025a41f9c969efafb2c42fb", "size": 3685, "ext": "py", "lang": "Python", "max_stars_repo_path": "ex2.py", "max_stars_repo_name": "fredericoschardong/programming-exercise-2-logistic-regression-university-of-stanford", "max_stars_repo_head_hexsha": "a8f0a224ba69c2cc4f4d0fb0e4acd5db0ce99cec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex2.py", "max_issues_repo_name": "fredericoschardong/programming-exercise-2-logistic-regression-university-of-stanford", "max_issues_repo_head_hexsha": "a8f0a224ba69c2cc4f4d0fb0e4acd5db0ce99cec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex2.py", "max_forks_repo_name": "fredericoschardong/programming-exercise-2-logistic-regression-university-of-stanford", "max_forks_repo_head_hexsha": "a8f0a224ba69c2cc4f4d0fb0e4acd5db0ce99cec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 102, "alphanum_fraction": 0.6575305292, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812336438725, "lm_q2_score": 0.9362850079703713, "lm_q1q2_score": 0.9066808310606111}} {"text": "from sympy import lambdify, diff, latex, symbols\nfrom utils import r\n\ndef newton_raphson(fn, xi, iter=1):\n x = symbols('x')\n \n out_str = \"\"\n dev_fn = lambdify(x, diff(fn))\n f = lambdify(x, fn)\n\n if iter == 1:\n out_str += f\"Newton-Raphson method is given as:\\n\"\n out_str += f\"$$ x_{{i+1}} = x_i - \\\\frac{{f(x_i)}}{{f'(x_i)}} $$\\n\"\n out_str += f\"Here $$ f(x) = {latex(fn)} $$\\n $$ f'(x)= {latex(diff(fn))} $$\\n\"\n \n out_str += f\"\\\\textbf{{Iteration {iter}}}\\n\\n\"\n out_str += f\"$$ x_{iter} = x_{iter - 1} - \\\\frac{{f(x_{iter - 1})}}{{f'(x_{iter - 1})}} $$\\n\"\n out_str += f\"$$ f(x_{iter-1}) = f({r(xi)}) = {r(f(xi))} $$\\n\"\n out_str += f\"$$ f'(x_{iter-1}) = f'({r(xi)}) = {r(dev_fn(xi))} $$\\n\"\n out_str += f\"$$ x_{iter} = {r(xi)} - \\\\left[\\\\frac{{{r(f(xi))}}}{{{r(dev_fn(xi))}}}\\\\right] $$\\n\"\n x_val = xi - (f(xi) / dev_fn(xi))\n out_str += f\"$$ x_{iter} = {r(x_val)} $$\\n\"\n\n error = None\n if iter > 1:\n out_str += \"\\n\\\\textbf{Error}\\n\\n\"\n out_str += f\"$$ \\\\text{{Error}} = \\\\frac{{\\\\left|\\\\text{{latest value}} - \\\\text{{previous value}}\\\\right|}}{{\\\\left|\\\\text{{latest value}}\\\\right|}} \\\\times 100 $$\\n\"\n out_str += f\"$$ \\\\text{{Error}} = \\\\frac{{\\\\left|{r(x_val)} - {r(xi)}\\\\right|}}{{\\\\left|{r(x_val)}\\\\right|}} \\\\times 100 $$\\n\"\n error = abs(x_val - xi)/abs(x_val) * 100\n out_str += f\"$$ \\\\text{{Error}} = {r(error, 2)} \\\\% $$\\n\"\n\n\n if error is not None and error < 0.0001:\n return out_str\n\n out_str += newton_raphson(fn, x_val, iter+1)\n return out_str\n\n\nif __name__ == '__main__':\n from sympy import exp\n x = symbols('x')\n\n print(newton_raphson(exp(-1 * x) - x, 0))\n # print(newton_raphson(28.16*x**2 - 3.14*x**3 - 90, 0))\n", "meta": {"hexsha": "4ac8e771bf08de32d0afadefff194de3666a7fd6", "size": 1756, "ext": "py", "lang": "Python", "max_stars_repo_path": "NC/newton_raphson.py", "max_stars_repo_name": "nmanumr/comsats-scripts", "max_stars_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-07-04T16:43:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T16:10:50.000Z", "max_issues_repo_path": "NC/newton_raphson.py", "max_issues_repo_name": "nmanumr/comsats-scripts", "max_issues_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NC/newton_raphson.py", "max_forks_repo_name": "nmanumr/comsats-scripts", "max_forks_repo_head_hexsha": "ec7a38c705315170f689f26ce6f6c56bbd87d923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1739130435, "max_line_length": 175, "alphanum_fraction": 0.5039863326, "include": true, "reason": "from sympy", "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239907775086, "lm_q2_score": 0.934395164824565, "lm_q1q2_score": 0.9065874785448722}} {"text": "# Assignement on Probability\n\nimport numpy as np\n'''\n1.Three coins are tossed. Find the probability of getting\na)At least one head\nb)Exactly 2 heads\n'''\nprint(\"Assignment 1\")\nss=2**3 # Sample Space\nprint(\"Probability of at least one Head:\",7/ss)\nprint(\"Probability of excatly two Heads:\",3/ss)\nprint(\"\\n\")\n\n'''\n2.An integer is chosen at random out of the integers from 1 to 100. What is the probability that it is\na)Multiple of 5\nb)Divisible by 7\nc)Greater than 70\n'''\nprint(\"Assignment 2\")\nnumbers=np.arange(1,101)\n\n#multiple of 5\ncount=0\nfor i in numbers:\n if i % 5 == 0:\n count+=1\nprint(\"Probability of Muliples of 5:\",count/len(numbers))\n\n#Divisible by 7\ncount=0\nfor i in numbers:\n if i % 7 == 0:\n count+=1\nprint(\"Probability of Divisible by 7:\",count/len(numbers))\n\n#Greater than 70\ncount=0\nfor i in numbers:\n if i > 70:\n count+=1\nprint(\"Probability of greater than 70:\",count/len(numbers))\nprint(\"\\n\")\n\n'''\n3.Generate Prime Numbers till 1000 and find the following among this population\na)Mean\nb)Median\nc)Range\nd)Quartile (1st , 2nd and 3rd )\ne)Inter-Quartile Range\nf)Variance\ng)Standard Deviation\n'''\n\nprint(\"Assignment 3\")\n\n# Function to generate Numpy array of Prime numbers\n\ndef bha_prime_gen(n):\n primeno=np.array([])\n for num in np.arange(2,n+1):\n flag=0\n for i in np.arange(2,int(num/2)):\n if (num%i==0):\n flag=1\n if(flag==0):\n primeno=np.append(primeno,num)\n return primeno\n\nprimes=bha_prime_gen(1000)\n#print(primes)\n\nprint(\"Mean:\",np.mean(primes))\nprint(\"Median:\",np.median(primes))\nprint(\"Range:\",np.max(primes)-np.min(primes))\nprint(\"Quartiles\")\nprint(\"1st Quartiles\",np.percentile(primes,25))\nprint(\"2st Quartiles\",np.percentile(primes,50))\nprint(\"3st Quartiles\",np.percentile(primes,75))\nprint(\"InterQuartile Range\",\n np.percentile(primes,75)-np.percentile(primes,25))\nprint(\"Variance\",np.var(primes))\nprint(\"Standard Deviations\",np.std(primes))", "meta": {"hexsha": "fe1060160185b20e856e1f255aea4adb80daf5a3", "size": 1968, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/simplePrograms/probability.py", "max_stars_repo_name": "BharathC15/NielitChennai", "max_stars_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/simplePrograms/probability.py", "max_issues_repo_name": "BharathC15/NielitChennai", "max_issues_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/simplePrograms/probability.py", "max_forks_repo_name": "BharathC15/NielitChennai", "max_forks_repo_head_hexsha": "c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-11T08:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T08:04:43.000Z", "avg_line_length": 23.1529411765, "max_line_length": 102, "alphanum_fraction": 0.6839430894, "include": true, "reason": "import numpy", "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.978712648206549, "lm_q2_score": 0.9263037241905732, "lm_q1q2_score": 0.9065851709461447}} {"text": "\nimport numpy as np\nimport pandas as pd\nimport random\nfrom collections import Counter\nimport math\n\n\ninf = float(1e-20)\n\n\ndef rootX2(x):\n aux = 0\n for i in range(len(x)):\n aux += (x[i])**2\n return np.sqrt(aux)\n\n\ndef dot_product(x, y):\n return np.dot(x, y)\n\n\ndef cosine_distance(x, y):\n return sum(a*b for a, b in zip(x, y))/(inf+float(rootX2(x)*rootX2(y)))\n\n\ndef euc_distance(x, y):\n aux = 0\n for i in range(len(x)):\n aux += (x[i]-y[i])**2\n return np.sqrt(aux)\n\n\ndef moda(s):\n lf = Counter(s).items()\n x = sorted(lf, key=lambda x: x[1])\n return x[-1][0]\n\n\ndef norma(x):\n aux = 0\n for i in range(len(x)):\n aux += (x[i])**2\n return np.sqrt(aux)\n\n\ndef manhattan_distance(x, y):\n return sum(abs(a-b) for a, b in zip(x, y))\n\n\nx = [6, 1, 3, 2]\ny = [3, 1, 1, 4]\nz = [6, 2, 2, 8]\na = [1, 2, 1]\nb = [3, 1, 2]\ncd = [(1, 2), (5, 6), (11, 3)]\n\nprint(list(zip(x, y)))\nprint(list(zip(a, b)))\nc, d = zip(* cd)\nprint('cd:', c, d)\n\nprint('Distance X - Y:', euc_distance(x, y))\nprint('Distance Y - Z:', euc_distance(y, z))\n\nprint('Norma X:', norma(x))\nprint('Norma Y:', norma(y))\n\nprint('Moda X:', moda(x))\nprint('Moda Y:', moda(y))\n\nprint('Manhattan Distance X - Y:', manhattan_distance(x, y))\nprint('Manhattan Distance Y - Z:', manhattan_distance(x, z))\n\nprint('Euclidian Distance X - Y:', euc_distance(x, y))\nprint('Euclidian Distance Y - Z:', euc_distance(y, z))\n\nprint('Cosine Distance X - Y:', cosine_distance(x, y))\nprint('Cosine Distance Y - Z:', cosine_distance(y, z))\n\nprint('Distancia De Manhattan: é a distância entre dois pontos medidos ao longo dos eixos em ângulos retos. É frequentemente utilizada em circuitos integrados onde os fios so correm em paralelo as eixos (X, Y).\\n')\nprint('Distancia Euclidiana: represente a distancia ''em linha reta'' entre dois pontos dentro de um espaço euclidiano. É calculada a partir da norma e o quadrado da diferença entre os pontos x-y.\\n')\nprint('A Norma de um Vetor: representa o comprimento desse vetor, que pode ser calculado por meio da distância de seu ponto final até a origem.\\n')\nprint('Produtor Escalar: Dados os vetores u=(a,b) e v=(c,d), definimos o produto escalar entre os vetores u e v, como o número real obtido por: u.v = a.c + b.d .\\n')\n\nprint('Dot Product X - Y:', dot_product(x, y))\n\nprint('Cosine Distance X - X:', cosine_distance(x, x))\nprint('Manhattan Distance X- X:', manhattan_distance(x, x))\nprint('Euclidian Distance X - X:', euc_distance(x, x))\n\nprint('Arquivos ''Comma Separeted Values'', ou seja, arquivos com valores separados por vírgulas.\\n')\n\nprint('O leitor (reader) do pacote CSV, retorna uma lista de linhas onde cada linha é uma string (F ou T)? F, segundo a documentação da biblioteca ele retorna um Reader Object, pelo qual é possivel iterar por todas as linhas do arquivo.\\n')\nprint('O leitor (reader) do pacote CSV, retorna uma lista de listas; cada linha é uma lista de campos string (F ou T)? F, ver reposta acima.\\n')\n\nanswers = ['1.a', '2.e', '3.c', '4.b', '5.a',\n '6.b', '7.a', '8.c', '9.d', '10.b']\nstudent_answers = ['1.a', '2.b', '3.c', '4.b',\n '5.c', '6.b', '7.a', '8.c', '9.a', '10.b']\nacc = 0\nfor question in student_answers:\n if question in answers:\n acc += 1\n\nprint(\"Accuracy:\", acc / len(answers))\n\nprint('random.sample(population, k) -> Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.\\n')\nprint('random.shuffle(x, random) -> Shuffle method takes two parameters. Out of the two random is an optional parameter. Shuffle method used to shuffle the sequence in place. i.e., it changes the position of items in a list. We call it a randomizes the elements of a list in place.\\n')\n\nprint('Range(1,10):',list(range(1, 10)), '\\n')\n\narray = [i for i in range(1, 101)]\narray = random.sample(array, 100)\n\nlista1, lista2 = array[30:], array[:30]\n\nrandom.shuffle(lista1)\nrandom.shuffle(lista2)\n\nprint('Shuffle Lista 1:', lista1, '\\n')\nprint('Shuffle Lista 2:', lista2, '\\n')\n\n# lista1.sort(key=lambda x: x[0])\n# lista1.sort(key=lambda x: x[1])\n# lista1.sort(key=lambda x: x[2])\nprint(lista1)\n\nprint('A função array.sort() ordena um vetor em ordem crescente ou descrecente (reverse = True).\\n')\nprint('Na função array.sort(key=lambda x: x[0]), key é uma função que será chamada para transformar a coleção de itens antes dele serem comparados, o paramêtro passado para key deve ser algo que seja callable. Na lista criada elas não conseguem iterar com x[0,1,2], no entanto a ideia seria transformar todos os itens da lista para que eles fossem iguais aos 1,2,3º itens.\\n')\nprint('Instance-Based Learning: é uma família de algoritmos de aprendizado que compararam novas instâncias de problemas/testes com as vistas em treinamento, ao invés de comparar com as instâncias armazenadas na memória. Um exemplo de algoritmo IBL é k-nearest neighbors.\\n')\nprint('O ''k'' em IBK significa K-Nearest Neighbors(K-NN), que significa K Vizinhos +Próximos. Nesse caso o K faz relação ao número de vizinhos mais próximos analisados, por exemplo em IBK3 nos procuramos o resultado nos 3 vizinhos mais próximos.\\n')\n\ns = [1,2,3,4,1,2,3,3,1,2,3,4,5]\n\nprint('Moda S:', moda(s))\n\nprint('A moda é necessária quando levamos em conta o conjunto que mais aparece dentro de um DataFrame, já que ela mostra o item que teve maior ocorrência. Desta forma, quando levamos em conta também a relação entre item e dataFrame, a moda é muito útil.\\n')\n\nprint('A função Counter() retorna os valores de X em dicionários. Os elementos são salvos como as chaves do dicionário e sua contagem (nº de ocorrências) como os valores do dicionário\\n')\n\nprint('Counter(x).keys():',Counter(x).keys())\nprint('Counter(x).value():',Counter(x).values())\nprint('Counter(x).items():',Counter(x).items())\nprint()\n\naux = ['aa', 'bb', 'cc', 'dd', 'aa', 'bb', 'cc', 'aa']\nprint('Moda [''aa'', ''bb'', ..]:', moda(aux))\naux = [1,2,3,1,4,5,6,1,2,3,5,6,6,7,8,4,5,6,7]\nprint('Moda [1,2,3,..]:', moda(aux))", "meta": {"hexsha": "a928dccf140c64aa432e51615f1f5802c595f3ee", "size": 6003, "ext": "py", "lang": "Python", "max_stars_repo_path": "IA/exercices.py", "max_stars_repo_name": "jvcanavarro/Classes", "max_stars_repo_head_hexsha": "1205c0701a4d3fc92fee33af7665957ac06745e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IA/exercices.py", "max_issues_repo_name": "jvcanavarro/Classes", "max_issues_repo_head_hexsha": "1205c0701a4d3fc92fee33af7665957ac06745e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IA/exercices.py", "max_forks_repo_name": "jvcanavarro/Classes", "max_forks_repo_head_hexsha": "1205c0701a4d3fc92fee33af7665957ac06745e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.02, "max_line_length": 376, "alphanum_fraction": 0.6768282525, "include": true, "reason": "import numpy", "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728096, "lm_q2_score": 0.9390248234010296, "lm_q1q2_score": 0.9065168715679038}} {"text": "\nimport numpy as np\n\n######################################################################################################\n# Transpose \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n######################################################################################################\n#\n# Getting the transpose of a matrix is really easy in NumPy. Simply access its T attribute. \n# There is also a transpose() function which returns the same thing, but you’ll rarely see that used\n# anywhere because typing T is so much easier. :)\n\n# For example:\n\nm = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\nprint(m)\n# displays the following result:\n# array([[ 1, 2, 3, 4],\n# [ 5, 6, 7, 8],\n# [ 9, 10, 11, 12]])\n\nprint('Transpose: ', m.T)\n# displays the following result:\n# array([[ 1, 5, 9],\n# [ 2, 6, 10],\n# [ 3, 7, 11],\n# [ 4, 8, 12]])\n\n# NumPy does this without actually moving any data in memory - it simply changes the way it indexes the\n# original matrix - so it’s quite efficient.\n#\n# However, that also means you need to be careful with how you modify objects.\n# For example, with the same matrix m from above, look what happens if we modify a value in its transpose:\n\nm_t = m.T\nm_t[1][1] = 200\n\nprint(m_t)\n# displays the following result:\n# array([[ 1, 5, 9],\n# [ 2, 200, 10],\n# [ 3, 7, 11],\n# [ 4, 8, 12]])\n\nprint(m)\n# displays the following result:\n# array([[ 1, 2, 3, 4],\n# [ 5, 200, 7, 8],\n# [ 9, 10, 11, 12]])\n\n# Notice how it modified the original matrix! So its best to just consider the transpose as a different\n# view of your matrix, rather than a different matrix.\n# \n# A real use case\n# I don't want to get into too many details about neural networks because you haven't covered them yet,\n# but there is one place you will almost certainly end up using a transpose, or at least thinking about it.\n# \n# Let's say you have the following two matrices, called inputs and weights,\n\ninputs = np.array([[-0.27, 0.45, 0.64, 0.31]])\nprint('Inputs: ', inputs)\n# displays the following result:\n# array([[-0.27, 0.45, 0.64, 0.31]])\n\nprint('Inputs shape: ', inputs.shape)\n# displays the following result:\n# (1, 4)\n\nweights = np.array([[0.02, 0.001, -0.03, 0.036], \\\n [0.04, -0.003, 0.025, 0.009], [0.012, -0.045, 0.28, -0.067]])\n\nprint('Weights:', weights)\n# displays the following result:\n# array([[ 0.02 , 0.001, -0.03 , 0.036],\n# [ 0.04 , -0.003, 0.025, 0.009],\n# [ 0.012, -0.045, 0.28 , -0.067]])\n\nprint('Weights shape:', weights.shape)\n# displays the following result:\n# (3, 4)\n\n# I won't go into what they're for because you'll learn about them later, but you're going to end up wanting\n# to find the matrix product of these two matrices.\n#\n# If you try it like they are now, you get an error:\n\n# np.matmul(inputs, weights)\n# displays the following error:\n# ValueError: shapes (1,4) and (3,4) not aligned: 4 (dim 1) != 3 (dim 0)\n#\n# If you did the matrix multiplication lesson, then you've seen this error before. \n# It's complaining of incompatible shapes because the number of columns in the left matrix, 4, does not equal\n# the number of rows in the right matrix, 3.\n\n# So that doesn't work, but notice if you take the transpose of the weights matrix, it will:\n\nprint('Inputs * weights.T', np.matmul(inputs, weights.T))\n# displays the following result:\n# array([[-0.01299, 0.00664, 0.13494]])\n\n# It also works if you take the transpose of inputs instead and swap their order, like we showed in the video:\n\nprint(np.matmul(weights, inputs.T))\n# displays the following result:\n# array([[-0.01299],# \n# [ 0.00664],\n# [ 0.13494]])\n\n# The two answers are transposes of each other, so which multiplication you use really just depends\n# on the shape you want for the output.\n", "meta": {"hexsha": "5e56c1e6472c6ed1acdddae4da92dc4835e6087c", "size": 3800, "ext": "py", "lang": "Python", "max_stars_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/transpose_demo.py", "max_stars_repo_name": "vanyaland/deep-learning-foundation", "max_stars_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-04-18T13:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-02T13:32:16.000Z", "max_issues_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/transpose_demo.py", "max_issues_repo_name": "ivan-magda/deep-learning-foundation", "max_issues_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-neural-networks/matrix-math-NumPy-refresher/transpose_demo.py", "max_forks_repo_name": "ivan-magda/deep-learning-foundation", "max_forks_repo_head_hexsha": "05a0df56c8223547bd7e8b62653a67f265c8e5ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5454545455, "max_line_length": 110, "alphanum_fraction": 0.6084210526, "include": true, "reason": "import numpy", "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.9481545366464882, "lm_q1q2_score": 0.9064180564600657}} {"text": "import random\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt \n\n\n# Calculating Pi using Monte Carlo algorithm.\ndef montecarlo_pi(times:int):\n inside = 0\n total = times\n\n for i in range(times):\n x_i = random.random()\n y_i = random.random()\n delta = x_i ** 2 + y_i **2 - 1\n\n if delta <= 0:\n inside += 1\n \n approx_pi = 4 * inside / total\n print('\\nRandom test: ' + str(times))\n print('Approximation of pi is:{:.8f}'.format(approx_pi))\n\n return approx_pi\n\n\nif __name__ == '__main__':\n numlist = [100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000, 5000000, 10000000, 30000000, 50000000, 75000000, 100000000]\n x_list = list(np.log10(numlist))\n pi_ = []\n for times in numlist:\n pi_.append(montecarlo_pi(times))\n\n plt.figure()\n plt.plot([min(x_list), max(x_list)], [math.pi, math.pi], color='red', label='true value')\n plt.plot(x_list, pi_, 'b.-', label='approximation')\n\n plt.legend()\n plt.xlabel('log10(n)')\n plt.ylabel('pi')\n\n my_y_ticks = np.arange(3, 3.4, 0.02)\n plt.yticks(my_y_ticks)\n plt.ylim((min(pi_)-0.1, max(pi_)+0.1))\n\n plt.show()\n", "meta": {"hexsha": "44c8a027341f8a3f03056df8259a9f5ad9e1dbc6", "size": 1173, "ext": "py", "lang": "Python", "max_stars_repo_path": "others/montecarlo.py", "max_stars_repo_name": "1lch2/PythonExercise", "max_stars_repo_head_hexsha": "9adbe5fc2bce71f4c09ccf83079c44699c27fce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-19T09:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-19T09:26:20.000Z", "max_issues_repo_path": "others/montecarlo.py", "max_issues_repo_name": "1lch2/PythonExercise", "max_issues_repo_head_hexsha": "9adbe5fc2bce71f4c09ccf83079c44699c27fce4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/montecarlo.py", "max_forks_repo_name": "1lch2/PythonExercise", "max_forks_repo_head_hexsha": "9adbe5fc2bce71f4c09ccf83079c44699c27fce4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9574468085, "max_line_length": 135, "alphanum_fraction": 0.610400682, "include": true, "reason": "import numpy", "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9796676448764483, "lm_q2_score": 0.92522995296862, "lm_q1q2_score": 0.906417848993915}} {"text": "# Load modules\nfrom __future__ import print_function\nimport os\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Change working Directory\nos.chdir('C:/Users/pp9596/Documents/02 ZSP/00 PACKT/Book - Practical Time-Series Analysis/Avishek')\n\n\n# Load Dataset\nibm_df = pd.read_csv('datasets/ibm-common-stock-closing-prices.csv')\nibm_df.head()\n\n#Rename the second column\nibm_df.rename(columns={'IBM common stock closing prices': 'Close_Price'},\n inplace=True)\nibm_df.head()\n\n# Function for Sigle exponential smoothing\ndef single_exp_smoothing(x, alpha):\n F = [x[0]] # first value is same as series\n for t in range(1, len(x)):\n F.append(alpha * x[t] + (1 - alpha) * F[t-1])\n return F\n\nibm_df['SES'] = single_exp_smoothing(ibm_df['Close_Price'], 0.8)\n\n\n### Plot Single Exponential Smoothing forecasted value\nfig = plt.figure(figsize=(5.5, 5.5))\nax = fig.add_subplot(2,1,1)\nibm_df['Close_Price'].plot(ax=ax)\nax.set_title('IBM Common Stock Close Prices during 1962-1965')\nax = fig.add_subplot(2,1,2)\nibm_df['SES'].plot(ax=ax, color='r')\nax.set_title('Single Exponential Smoothing')\nplt.savefig('plots/ch2/B07887_02_14.png', format='png', dpi=300)\n\n\n# Plot the forecasted values using multiple alpha values\n#Calculate the moving averages using 'rolling' and 'mean' functions\nibm_df['SES2'] = single_exp_smoothing(ibm_df['Close_Price'], 0.2)\nibm_df['SES6']= single_exp_smoothing(ibm_df['Close_Price'], 0.6)\nibm_df['SES8']= single_exp_smoothing(ibm_df['Close_Price'], 0.8)\n\n# Plot the curves\nf, axarr = plt.subplots(3, sharex=True)\nf.set_size_inches(5.5, 5.5)\n\nibm_df['Close_Price'].iloc[:45].plot(color='b', linestyle = '-', ax=axarr[0])\nibm_df['SES2'].iloc[:45].plot(color='r', linestyle = '--', ax=axarr[0])\naxarr[0].set_title('Alpha 0.2')\n\nibm_df['Close_Price'].iloc[:45].plot(color='b', linestyle = '-', ax=axarr[1])\nibm_df['SES6'].iloc[:45].plot(color='r', linestyle = '--', ax=axarr[1])\naxarr[1].set_title('Alpha 0.6')\n\nibm_df['Close_Price'].iloc[:45].plot(color='b', linestyle = '-', ax=axarr[2])\nibm_df['SES8'].iloc[:45].plot(color='r', linestyle = '--', ax=axarr[2])\naxarr[2].set_title('Alpha 0.8')\nplt.savefig('plots/ch2/B07887_02_15.png', format='png', dpi=300)\n\n", "meta": {"hexsha": "fe9a6bf56b014f2f62b0ccf255056e30ac946033", "size": 2221, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter03/Chapter_3_simpleExponentialSmoothing.py", "max_stars_repo_name": "stciaischoolrnn/Practical-Time-Series-Analysis", "max_stars_repo_head_hexsha": "72eeabbcf2a3af742b2a114026cfd841b0ea9184", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 267, "max_stars_repo_stars_event_min_datetime": "2017-10-04T10:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:54:44.000Z", "max_issues_repo_path": "Chapter03/Chapter_3_simpleExponentialSmoothing.py", "max_issues_repo_name": "stciaischoolrnn/Practical-Time-Series-Analysis", "max_issues_repo_head_hexsha": "72eeabbcf2a3af742b2a114026cfd841b0ea9184", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-08T10:11:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T07:48:48.000Z", "max_forks_repo_path": "Chapter03/Chapter_3_simpleExponentialSmoothing.py", "max_forks_repo_name": "stciaischoolrnn/Practical-Time-Series-Analysis", "max_forks_repo_head_hexsha": "72eeabbcf2a3af742b2a114026cfd841b0ea9184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215, "max_forks_repo_forks_event_min_datetime": "2017-09-28T13:52:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T14:14:37.000Z", "avg_line_length": 34.1692307692, "max_line_length": 99, "alphanum_fraction": 0.7050877983, "include": true, "reason": "import numpy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018426872776, "lm_q2_score": 0.9294403999037784, "lm_q1q2_score": 0.9063919906541649}} {"text": "import numpy as np\n\ndef vec_abs(x):\n \"\"\"Returns the length of a vector (or list of vectors)\"\"\"\n return np.sqrt(np.sum(x**2, axis=x.ndim-1))\n\ndef normalise(u):\n return u / vec_abs(u)\n\ndef project(u, v):\n return u * (np.dot(u, v) / np.dot(u, u))\n\ndef gram_schmidt(vs, normalised=True):\n \"\"\"Gram-Schmidt Orthonormalisation / Orthogonisation.\n Given a set of vectors, returns an orthogonal set of vectors\n spanning the same subspace.\n Set `normalised` to False to return a non-normalised set of vectors.\"\"\"\n us = []\n for v in np.array(vs):\n u = v - np.sum([project(x, v) for x in us], axis=0)\n us.append(u)\n if normalised:\n return np.array([normalise(u) for u in us])\n else:\n return np.array(us)\n\n\ndef gram_schmidt_modified(vs, normalised=True):\n \"\"\"Gram-Schmidt Orthonormalisation / Orthogonisation.\n Given a set of vectors, returns an orthogonal set of vectors\n spanning the same subspace.\n Set `normalised` to False to return a non-normalised set of vectors.\n\n (Modified version as per p.80 Practical Numerical Algorithms\n - Parker & Chua)\"\"\"\n us = []\n for v in np.array(vs):\n u = v\n for x in us:\n u = u - project(x, u)\n us.append(u)\n if normalised:\n return np.array([normalise(u) for u in us])\n else:\n return np.array(us)\n\n\nif __name__ == '__main__':\n ## testing Gram-Schmidt works as expected\n print(\"Testing Gram-Schmidt orthonormalisation.\")\n\n randmat = np.random.random((3,3))\n print(\"Random matrix:\")\n print(randmat)\n gsrm = gram_schmidt(randmat)\n print(\"Normalised:\")\n print(gsrm)\n print(\"x1 . x2 = \", np.dot(gsrm[0], gsrm[1]))\n print(\"x1 . x3 = \", np.dot(gsrm[0], gsrm[2]))\n print(\"x2 . x3 = \", np.dot(gsrm[1], gsrm[2]))\n print(\"x2 . x2 = \", np.dot(gsrm[1], gsrm[1]))\n", "meta": {"hexsha": "f67b8a9732c584f998914b1ffbb7fe657e55cb9d", "size": 1856, "ext": "py", "lang": "Python", "max_stars_repo_path": "jpy/maths/vector.py", "max_stars_repo_name": "jamesp/jpy", "max_stars_repo_head_hexsha": "ae3085d590f5e3ad4b0d8174fae24cd3c9ae7e63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jpy/maths/vector.py", "max_issues_repo_name": "jamesp/jpy", "max_issues_repo_head_hexsha": "ae3085d590f5e3ad4b0d8174fae24cd3c9ae7e63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jpy/maths/vector.py", "max_forks_repo_name": "jamesp/jpy", "max_forks_repo_head_hexsha": "ae3085d590f5e3ad4b0d8174fae24cd3c9ae7e63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.935483871, "max_line_length": 75, "alphanum_fraction": 0.614762931, "include": true, "reason": "import numpy", "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214470715363, "lm_q2_score": 0.9399133515091156, "lm_q1q2_score": 0.9063786032491279}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef mse(m,b,xv,yv):\n N = len(xv)\n error = 0\n for i in range(N):\n error += (yv[i] - (m*xv[i] + b))**2\n error /= N\n return error \n\ndef stepGradient(b_current,m_current,xv,yv,gamma):\n #gradient descent \n b_gradient = 0\n m_gradient = 0\n N = len(xv)\n for i in range(N):\n m_gradient += xv[i]*(yv[i]-(m_current*xv[i] + b_current))\n b_gradient += (yv[i]-(m_current*xv[i] + b_current))\n m_gradient = m_gradient*(-2.0/N)\n b_gradient = b_gradient*(-2.0/N)\n\n m_new = m_current - gamma*m_gradient\n b_new = b_current - gamma*b_gradient\n #stdout = \"dEdm=%f, dEdb=%f\"%(m_gradient,b_gradient)\n #print(stdout)\n return [m_new,b_new,m_gradient,b_gradient]\n\ndef get_mse_weights(b_init,m_init,xv,yv,gamma,iterations):\n m = m_init\n b = b_init\n \n mse_vec = []\n m_gradient_vec = []\n b_gradient_vec = []\n for i in range(iterations):\n m,b,m_gradient,b_gradient = stepGradient(b,m,xv,yv,gamma)\n mse_vec.append(mse(m,b,xv,yv))\n m_gradient_vec.append(m_gradient)\n b_gradient_vec.append(b_gradient)\n\n return [m,b,mse_vec,m_gradient_vec,b_gradient_vec] \n\ndef main():\n #Number of points \n N = 100\n\n #(xi,yi) generate\n #Xv = np.random.randint(1,10,size=N)\n #Yv = np.random.randint(1,10,size=N)\n mu,sigma = 2,5\n Xv = np.random.normal(mu,sigma,size=N)\n Yv = np.random.normal(mu,sigma,size=N)\n \n for i in range(N): \n stdout = \"(X%d,Y%d)=(%d,%d)\"%(i,i,Xv[i],Yv[i])\n print(stdout)\n\n mse_vec = []\n m,b,mse_vec,m_gradient_vec,b_gradient_vec = get_mse_weights(1,1,Xv,Yv,0.01,10000)\n\n x_min = np.min(Xv)\n x_max = np.max(Xv)\n xl = np.arange(x_min,x_max)\n yl = []\n for x in xl: \n yl.append(x*m + b)\n\n #print last \n stdout = \"mse_final=%f, dEdm_final=%f, dEdb_final=%f\"%(mse_vec[-1],m_gradient_vec[-1],b_gradient_vec[-1])\n print(stdout)\n \n #plot\n plt.figure(1)\n plt.plot(Xv,Yv,'ro')\n plt.plot(xl,yl)\n\n #figure 2\n plt.figure(2)\n plt.subplot(221)\n plt.plot(mse_vec)\n plt.xlabel('mse')\n plt.subplot(222)\n plt.plot(m_gradient_vec,color='blue')\n plt.xlabel('m_gradient')\n plt.subplot(224)\n plt.plot(b_gradient_vec,color='green')\n plt.xlabel('b_gradient')\n plt.show()\n\n\n\n\nif __name__ == \"__main__\":\n main()\n", "meta": {"hexsha": "4e46e7979f074c7bd5be38dec6fdf87ab37523ab", "size": 2369, "ext": "py", "lang": "Python", "max_stars_repo_path": "example.py", "max_stars_repo_name": "louipr/linear_regression", "max_stars_repo_head_hexsha": "de4d087d476ffaa3611b45156300111bad4f2e17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example.py", "max_issues_repo_name": "louipr/linear_regression", "max_issues_repo_head_hexsha": "de4d087d476ffaa3611b45156300111bad4f2e17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.py", "max_forks_repo_name": "louipr/linear_regression", "max_forks_repo_head_hexsha": "de4d087d476ffaa3611b45156300111bad4f2e17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6770833333, "max_line_length": 109, "alphanum_fraction": 0.6036302237, "include": true, "reason": "import numpy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208032, "lm_q2_score": 0.9390248165754385, "lm_q1q2_score": 0.9055217680304215}} {"text": "import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\n\ndef covarience_matrix(X):\n #standardizing data\n X_std = StandardScaler().fit_transform(X)\n\n #sample means of feature columns' of dataset\n mean_vec = np.mean(X_std, axis=0) \n #covariance matrix\n cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1)\n #if right handside is ( Xstd - mean(Xstd) )^T . ( Xstd - mean(Xstd) )\n #simplyfying X^T.X / ( n - 1 )\n cov_mat = np.cov(X_std.T)\n return cov_mat\n\ndef max_min_bi_corel(X):\n a = covarience_matrix(X)\n a[a>=1] = 0\n maxcor = np.argwhere(a.max() == a)[0] # reverse 1\n\n b = covarience_matrix(x)\n mincor = np.argwhere(b.min() == b)[0] # reverse 1\n\n return maxcor,mincor\n\ndef eign_decomposition(cov_mat):\n #eign_decomposition\n eign_vals, eign_vecs = np.linalg.eig(cov_mat)\n\n print('Eigenvalues \\n%s' %eign_vals)\n print('\\nEigenvectors \\n%s' %eign_vecs)\n\n \n #for i in range(len(eig_vals)):\n # (np.abs(eig_vals[i]), eig_vecs[:,i] )\n #make a list of (eigenvalue, eigenvector) tuples\n eign_pairs = [ (np.abs(eign_vals[i]), eign_vecs[:,i] ) for i in range(len(eign_vals)) ]\n return eign_pairs\n\ndata = pd.read_csv('iris.csv')\ndata_features = data.ix[:,:-1]\ndata_label = data.ix[:,4]\n\n#covariance_matrix\ncov_mat = covarience_matrix(data_features)\n\n#eign_decomposition\neig_pairs = eign_decomposition(cov_mat)\n#Sorting the (eignvalue, eignvector) tuples from high to low\neig_pairs.sort()\neig_pairs.reverse()\n\n#you can select the principle components by eign values, which one can be dropped\n#visually confirming about the list is correctly sorted by decreasing eignvaluess\nprint(\"Eigenvalues in descending order:\")\nfor i in eig_pairs:\n print(i[0])\n \n#projection_matrix of our concatenated top k eigen vectors\nmatrix_w = np.hstack(( eig_pairs[0][1].reshape(4,1),\n eig_pairs[1][1].reshape(4,1),\n eig_pairs[2][1].reshape(4,1) ))\n\nprint(\"Matrix W:\\n\", matrix_w)\n'''\nwe can choose how many dimensions we want for our subspace by chosing that amount of eignvectors\nto construct our dxk dimensional eignvector matrix w. lastly we will use our projection matrix\nto transform our samples onto to the subspaces via a simple dot product operation.\n'''\n", "meta": {"hexsha": "c4b89372a92ff2f76d7f2b0b7a45c55eb9e0ae70", "size": 2314, "ext": "py", "lang": "Python", "max_stars_repo_path": "pca.py", "max_stars_repo_name": "ShaonMajumder/principle_component_analysis", "max_stars_repo_head_hexsha": "0c9d8d59d28521f38cc354432c2f062cdccbdfc3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-23T09:47:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-23T09:53:14.000Z", "max_issues_repo_path": "pca.py", "max_issues_repo_name": "ShaonMajumder/Principle_Component_Analysis_scratch", "max_issues_repo_head_hexsha": "0c9d8d59d28521f38cc354432c2f062cdccbdfc3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pca.py", "max_forks_repo_name": "ShaonMajumder/Principle_Component_Analysis_scratch", "max_forks_repo_head_hexsha": "0c9d8d59d28521f38cc354432c2f062cdccbdfc3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1388888889, "max_line_length": 96, "alphanum_fraction": 0.6918755402, "include": true, "reason": "import numpy", "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018383629826, "lm_q2_score": 0.9284088050123334, "lm_q1q2_score": 0.9053859734004073}} {"text": "#Fibonacci number\n\nimport numpy as np\n\ndef __pow(x,n,I):\n if n==0:\n return I\n elif n==1:\n return x\n else:\n y = __pow(x,n//2,I)\n y = y.dot(y)\n if n%2:\n y = x.dot(y)\n return y\n\ndef MatrixFibonacci(index):\n F = __pow(np.array(((1,1),(1,0)),dtype=object),index,np.eye(2))\n return F[0][1]\n\ndef MatrixFibonacci2(index):\n return np.linalg.matrix_power(np.matrix(((1,1),(1,0)),dtype=object),index)[0,1]\n\ndef RecursionFibonacci(index): \n if index==1: \n return 0\n elif index==2: \n return 1\n else: \n return RecursionFibonacci(index-1)+RecursionFibonacci(index-2) \n\ndef IterationFibonacci(index): \n a=0\n b=1\n if index == 0: \n return a \n elif index == 1: \n return b \n else: \n for i in range(2,index): \n c=a+b \n a=b \n b=c \n return b\n\ndef IterationFibonacciSequence(indexLimit): \n a=0\n b=1\n seq=[0,1]\n if indexLimit == 0: \n return a \n elif indexLimit == 1: \n return [a,b] \n else: \n for i in range(2,indexLimit): \n c=a+b \n a=b \n b=c \n seq.append(b)\n return seq\n\ndef Binetformula(index,roundi=True):\n from sympy import Pow as mmmpow\n from sympy import Integer as mmmint\n from sympy import N as mmmn\n b = (mmmpow(1.6185,index)-mmmpow(-0.6185,index))/2.237\n if(not roundi):\n return mmmint(b)\n else:\n return mmmn(b)\n\ndef isFibonacci(num):\n from math import log as mlog\n a = 2.07684408521711*mlog(2.237*num)\n return (a % 1 * 100 > 90) or (a % 1 * 100 < 5)\n\ndef isFibonacci2(num):\n from math import log as mlog\n a=(mlog(( (num*5**(1/2)+(5*num**2 + 4)**(1/2))/2 ),1.618)+mlog(( (num*5**(1/2)+(5*num**2 - 4)**(1/2))/2 ),1.618))/2\n return (a % 1 * 100 > 99) or (a % 1 * 100 < 1)\n\ndef doTest(toPrint=False,toProgress=False,start=0,toEnd=1000,algo=\"s\"):\n s=set()\n KK=10000\n from IPython.display import clear_output\n for i in range(start,toEnd+1):\n if(toProgress and ( i=KK and i%(KK/100)==0))):\n clear_output(wait=True)\n print(i,end=\"\\t\")\n if(algo==\"s\"):\n fibon=MatrixFibonacci(i)\n elif(algo==\"binet\"):\n fibon=Binetformula(i)\n elif(algo==\"iterat\"):\n fibon=IterationFibonacci(i)\n elif(algo==\"recursive\"):\n fibon=RecursionFibonacci(i)\n if(fibon):\n s.add(fibon)\n if(toPrint and not toProgress):\n print(fibon,end=\", \")\n if(toProgress and (i=KK and i%(KK/100)==0))):\n print(s)\n if(not toPrint):\n return s\n \ndef CheckExists(toend=10000):\n for i in {Binetformula(i) for i in range(toend) if i!=0}:\n if(not isFibonacci(i)):\n print(i,end=\", \")\n \ndef IterationFibonacciWord(index):\n Sn_1=\"0\"\n Sn=\"01\"\n tmp=\"\" \n for i in range(2,index+1): \n tmp=Sn\n Sn+=Sn_1 \n Sn_1=tmp \n return Sn \n\ndef IterationFibonacciWords(indexLimit):\n Sn_1=\"0\"\n Sn=\"01\"\n tmp=\"\" \n word=[Sn_1,Sn]\n for i in range(2, indexLimit + 1): \n tmp=Sn\n Sn+=Sn_1 \n Sn_1=tmp \n word.append(Sn)\n return word\n\ndef FibonacciWord(index):\n from math import floor as mmmfloor\n return ((mmmfloor(index*1.618)-mmmfloor((index+1)*1.618))+2)\n\n#RecursionFibonacci(9)\n#IterationFibonacci(9)\n#MatrixFibonacci(8)\n#MatrixFibonacci2(8)\n#Binetformula(7)\n#isFibonacci(13)\n#doTest(True,False,1,5000) #823 ms\n#doTest(True,False,1,5000,\"binet\") #163 ms", "meta": {"hexsha": "4708a543629f66116a3b498754f9c2d01823bbac", "size": 3596, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Number Theory/FibonacciNumber.py", "max_stars_repo_name": "lonagi/pysasha", "max_stars_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Number Theory/FibonacciNumber.py", "max_issues_repo_name": "lonagi/pysasha", "max_issues_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Number Theory/FibonacciNumber.py", "max_forks_repo_name": "lonagi/pysasha", "max_forks_repo_head_hexsha": "e344afa03357b7c626c949aa31fac51574e97f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8, "max_line_length": 119, "alphanum_fraction": 0.5475528365, "include": true, "reason": "import numpy,from sympy", "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.9362850119705769, "lm_q1q2_score": 0.9053071036208464}} {"text": "import numpy as np\nfrom numpy.linalg import norm\n\n\nclass linearSys:\n def __init__(self, A, b):\n self.A = A\n self.b = b\n self.n = b.shape[0]\n self.x = np.zeros([self.n, 1])\n \n def JacobiIterative(self, XO, N, TOL):\n k = 1\n while k <= N:\n for i in range(self.n):\n self.x[i, 0] = (self.b[i] - np.dot(self.A[i, :], XO[:, 0]) + self.A[i, i] * XO[i, 0]) / self.A[i, i]\n \n indicator = norm(self.x - XO)\n if indicator < TOL:\n return self.x.reshape((-1,))\n \n k += 1\n XO = self.x\n \n return 'Maximum number of iterations exceeded'\n \n def GaussSeidelIterative(self, XO, N, TOL):\n k = 1\n while k <= N:\n for i in range(self.n):\n self.x[i, 0] = (self.b[i] - np.dot(self.A[i, 0:i], self.x[0:i, 0]) - np.dot(self.A[i, i+1:], XO[i+1:, 0])) / self.A[i, i]\n \n indicator = norm(self.x - XO)\n if indicator < TOL:\n return self.x.reshape((-1,))\n \n k += 1\n XO = self.x\n \n return 'Maximum number of iterations exceeded'\n \n \n def SOR(self, XO, N, TOL, omiga):\n k = 1\n while k <= N:\n for i in range(self.n):\n self.x[i, 0] = (1 - omiga) * XO[i, 0] + omiga * (self.b[i] - np.dot(self.A[i, 0:i], self.x[0:i, 0]) - np.dot(self.A[i, i+1:], XO[i+1:, 0])) / self.A[i, i]\n \n indicator = norm(self.x - XO, np.inf)\n if indicator < TOL:\n return self.x.reshape((-1,))\n \n k += 1\n XO = self.x\n \n return 'Maximum number of iterations exceeded'\n\n\nif __name__ == '__main__':\n # A = np.array([\n # [10, -1, 2, 0], \n # [-1, 11, -1, 3],\n # [2, -1, 10, -1],\n # [0, 3, -1, 8]\n # ])\n # b = np.array([6, 25, -11, 15])\n # XO = np.zeros([4, 1])\n A = np.array([\n [4, 3, 0], \n [3, 4, -1],\n [0, -1, 4]\n ])\n b = np.array([24, 30, -24])\n XO = np.ones([3, 1])\n N = 30\n TOL = 1e-6\n sol = linearSys(A, b)\n print('Jacobi:', sol.JacobiIterative(XO, N, TOL))\n print('Gauss-Seidel:', sol.GaussSeidelIterative(XO, N, TOL))\n print('SOR:', sol.SOR(XO, N, TOL, 1.241))", "meta": {"hexsha": "45690ea961bdd65c918c48fe7e85fc28ad1c1450", "size": 2349, "ext": "py", "lang": "Python", "max_stars_repo_path": "numerical_analysis/report6_codes.py", "max_stars_repo_name": "chaosWsF/Financial-Mathematics", "max_stars_repo_head_hexsha": "e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-13T11:57:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T11:57:56.000Z", "max_issues_repo_path": "numerical_analysis/report6_codes.py", "max_issues_repo_name": "chaosWsF/Financial-Mathematics", "max_issues_repo_head_hexsha": "e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical_analysis/report6_codes.py", "max_forks_repo_name": "chaosWsF/Financial-Mathematics", "max_forks_repo_head_hexsha": "e8eebb7edd24eb71f6161fb6bf5fea4bb8a2961a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3625, "max_line_length": 170, "alphanum_fraction": 0.423584504, "include": true, "reason": "import numpy,from numpy", "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964855157641556, "lm_q2_score": 0.9381240151413301, "lm_q1q2_score": 0.9051537945165176}} {"text": "from numpy import array, cos, sin, tan, identity\n\ndef Rx(phi):\n return array([\n [1, 0 , 0 ],\n [0, cos(phi),-sin(phi)],\n [0, sin(phi), cos(phi)]\n ])\n\ndef Ry(theta):\n return array([\n [ cos(theta), 0, sin(theta)],\n [ 0 , 1, 0 ],\n [-sin(theta), 0, cos(theta)]\n ])\n\ndef Rz(psi):\n return array([\n [cos(psi),-sin(psi), 0],\n [sin(psi), cos(psi), 0],\n [0 , 0 , 1]\n ])\n\ndef Hrx(phi):\n return array([\n [1, 0 , 0 , 0],\n [0, cos(phi),-sin(phi), 0],\n [0, sin(phi), cos(phi), 0],\n [0, 0 , 0 , 1]\n ])\n\ndef Hry(theta):\n return array([\n [ cos(theta), 0, sin(theta), 0],\n [ 0 , 1, 0 , 0],\n [-sin(theta), 0, cos(theta), 0],\n [ 0 , 0, 0 , 1]\n ])\n\ndef Hrz(psi):\n return array([\n [cos(psi),-sin(psi), 0, 0],\n [sin(psi), cos(psi), 0, 0],\n [0 , 0 , 1, 0],\n [0 , 0 , 0, 1]\n ])\n\ndef Htx(x):\n return array([\n [1, 0, 0, x],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ])\n\ndef Hty(y):\n return array([\n [1, 0, 0, 0],\n [0, 1, 0, y],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ])\n\ndef Htz(z):\n return array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, z],\n [0, 0, 0, 1]\n ])\n\ndef inv(H):\n '''\n Inverse homogenous transformation\n '''\n R = H[0:3,0:3]\n d = H[0:3,3]\n\n invH = identity(4)\n\n invH[0:3,0:3] = R.transpose()\n invH[0:3,3] = -R.transpose().dot(d)\n\n return invH\n\ndef DH(theta, d, a, alpha):\n '''\n Deneavit-Hartenberg transformation matrix\n ''' \n return array([\n [ cos(theta),-sin(theta)*cos(alpha), sin(theta)*sin(alpha), a*cos(theta)],\n [ sin(theta), cos(theta)*cos(alpha),-cos(theta)*sin(alpha), a*sin(theta)],\n [ 0 , sin(alpha) , cos(alpha) , d ],\n [ 0 , 0 , 0 , 1 ]\n ])\n", "meta": {"hexsha": "0c99e7996d2fdb8beb7831a058c8f690fd86c05f", "size": 2100, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/math3d.py", "max_stars_repo_name": "Orwatronic/mas_514", "max_stars_repo_head_hexsha": "81a1e34460b78cb9f0329c4c0527936971459b6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math3d.py", "max_issues_repo_name": "Orwatronic/mas_514", "max_issues_repo_head_hexsha": "81a1e34460b78cb9f0329c4c0527936971459b6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math3d.py", "max_forks_repo_name": "Orwatronic/mas_514", "max_forks_repo_head_hexsha": "81a1e34460b78cb9f0329c4c0527936971459b6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.875, "max_line_length": 82, "alphanum_fraction": 0.3657142857, "include": true, "reason": "from numpy", "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9770226267447513, "lm_q2_score": 0.9263037267336475, "lm_q1q2_score": 0.9050197002567605}} {"text": "import sys\n\nimport numpy as np\n\nprint('Python : {}'.format(sys.version))\n\nprint('Numpy : {}'.format(np.__version__))\n\nfrom numpy import linalg\n\n# Define an Array \nA=np.arange(9) - 3\nA\n\nB=A.reshape(3,3)\n\nB\n\n\n\n#Ecludian L2 norm - default\nprint(np.linalg.norm(A))\nprint(np.linalg.norm(B))\n\n#the frogeniuos norm is the L2 norm for a matrix\nprint(np.linalg.norm(B,'fro'))\n\n# the max norm ( p = infinity)\nprint(np.linalg.norm(A,np.inf))\nprint(np.linalg.norm(B,np.inf))\n\n# Vector normalization - normalization to produce a vector\nnorm = np.linalg.norm(A)\nA_unit = A / norm\nprint(A_unit)\n\n# the magnitude of a unit vector is equal to 1\nnp.linalg.norm(A_unit)\n\n#Eigendecomposition\n\n#The eigendecomposition is one form of matrix decomposition.\n#Decomposing a matrix means that we want to find a product of matrices that is equal to the initial matrix. \n#In the case of eigendecomposition, we decompose the initial matrix into the product of its eigenvectors and eigenvalues.\n#Before all, let’s see the link between matrices and linear transformation. Then, you’ll learn what are eigenvectors and eigenvalues.\n\n# find the eigen values and eigen vector for a simple squaematrix\n\nA =np.diag(np.arange(1,4))\nA\n\neigenvalues,eigenvectors = np.linalg.eig(A)\neigenvalues\n\neigenvectors\n\n# eigenvalue w[i] corresponds to the eigenvector v[:,i]\nprint('Eigenvalue : {}'.format(eigenvalues[2]))\nprint('Eigenvector : {}'.format(eigenvectors[:,1]))\n\nnp.diag(eigenvalues)\n\nnp.linalg.inv(eigenvectors)\n\n\n\n# verify eigen decomposition\n\nmatrix = np.matmul(np.diag(eigenvalues),np.linalg.inv(eigenvectors))\noutput = np.matmul(eigenvectors,matrix).astype(np.int)\nprint (output)\n\n\n\n# import necessary matplotlib libraries\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n%matplotlib inline\n\n# plot the eigen vectors\norigin = [0,0,0]\n\nfig = plt.figure(figsize=(18,10))\naxl = fig.add_subplot(121, projection='3d')\n\naxl.quiver(origin,origin,origin,eigenvectors[0,:],eigenvectors[1,:],eigenvectors[2,:],color='k')\naxl.set_xlim([-3,3])\naxl.set_ylim([-3,3])\naxl.set_zlim([-3,3])\naxl.set_xlabel('x axis')\naxl.set_ylabel('y axis')\naxl.set_zlabel('z axis')\naxl.view_init(15,30)\naxl.set_title('Before Multiplication')\n\n#show the plot\nplt.show()\n\n# plot the eigen vectors\norigin = [0,0,0]\n\nfig = plt.figure(figsize=(18,10))\naxl = fig.add_subplot(121, projection='3d')\n\naxl.quiver(origin,origin,origin,eigenvectors[0,:],eigenvectors[1,:],eigenvectors[2,:],color='k')\naxl.set_xlim([-3,3])\naxl.set_ylim([-3,3])\naxl.set_zlim([-3,3])\naxl.set_xlabel('x axis')\naxl.set_ylabel('y axis')\naxl.set_zlabel('z axis')\naxl.view_init(15,30)\naxl.set_title('Before Multiplication')\n\n# now lets multiply origin matrix by eigenvectors\nnew_eig = np.matmul(A, eigenvectors)\nax2 = plt.subplot(122,projection = '3d')\nax2.quiver(origin,origin,origin,new_eig[0,:],new_eig[1,:],new_eig[2,:],color='k')\n\n#add the eigenvalues to the plot\nax2.plot(eigenvalues[0]*eigenvectors[0],eigenvalues[1]*eigenvectors[1],eigenvalues[2]*eigenvectors[2],'rX')\nax2.set_xlim([-3,3])\nax2.set_ylim([-3,3])\nax2.set_zlim([-3,3])\nax2.set_xlabel('x axis')\nax2.set_ylabel('y axis')\nax2.set_zlabel('z axis')\nax2.view_init(15,30)\nax2.set_title('After Multiplication')\n#show the plot\nplt.show()\n\n\n\n", "meta": {"hexsha": "6ea181402a55770e3a4b26d500780a9462af276e", "size": 3223, "ext": "py", "lang": "Python", "max_stars_repo_path": "Mathematics_for_ML/eigen.py", "max_stars_repo_name": "sharmaronak79/python", "max_stars_repo_head_hexsha": "7d000a613087e522005083453630272bb48bb2ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mathematics_for_ML/eigen.py", "max_issues_repo_name": "sharmaronak79/python", "max_issues_repo_head_hexsha": "7d000a613087e522005083453630272bb48bb2ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mathematics_for_ML/eigen.py", "max_forks_repo_name": "sharmaronak79/python", "max_forks_repo_head_hexsha": "7d000a613087e522005083453630272bb48bb2ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8740740741, "max_line_length": 133, "alphanum_fraction": 0.7375116351, "include": true, "reason": "import numpy,from numpy", "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972414716174355, "lm_q2_score": 0.9304582598330264, "lm_q1q2_score": 0.9047913046476167}} {"text": "import numpy as np\n\n#Questions on Polynomial\n# Define a polynomial function\n#poly1d Return Polynomial and the operation applied\nnp.poly1d([4, 9, 5, 4])\n\n# How to add one polynomial to another using NumPy in Python?\n#polyadd Find the sum of two polynomials.\n# p(x) = 5(x**2) + (-2)x +5 == (5,-2,5) \n# q(x) = 2(x**2) + (-5)x +2 == (2,-5,2) \nnp.polynomial.polynomial.polyadd((5,-2,5) ,(2,-5,2) ) \n\n# How to subtract one polynomial to another using NumPy in Python?\n#polysub Difference (subtraction) of two polynomials.\n# p(x) = 5(x**2) + (-2)x +5 == (5,-2,5) \n# q(x) = 2(x**2) + (-5)x +2 == (2,-5,2) \nnp.polynomial.polynomial.polysub((5,-2,5) ,(2,-5,2)) \n\n# How to multiply a polynomial to another using NumPy in Python?\n#polymul Find the product of two polynomials.\n# p(x) = 5(x**2) + (-2)x +5 == (5,-2,5) \n# q(x) = 2(x**2) + (-5)x +2 == (2,-5,2) \nnp.polynomial.polynomial.polymul((5,-2,5) ,(2,-5,2)) \n\n# How to divide a polynomial to another using NumPy in Python?\n#polydiv Returns the quotient and remainder of polynomial division.\n# p(x) = 5(x**2) + (-2)x +5 == (5,-2,5) \n# q(x) = 2(x**2) + (-5)x +2 == (2,-5,2) \nnp.polynomial.polynomial.polydiv((5,-2,5) ,(2,-5,2)) \n\n# Find the roots of the polynomials using NumPy\n#roots Return an array containing the roots of the polynomial.\nnp.roots( [1, 2, 1] )\n\n# Evaluate a 2-D polynomial series on the Cartesian product\n# polygrid2d Return The values of the two dimensional polynomial\n# series at points in the Cartesian product of x and y.\nnp.polynomial.polynomial.polygrid2d([7, 9], [8, 10], \n np.array([[1, 3, 5], [2, 4, 6]])) \n\n# Evaluate a 3-D polynomial series on the Cartesian product\n# polygrid3d Return The values of the two dimensional polynomial \n# series at points in the Cartesian product of x and y.\nnp.polynomial.polynomial.polygrid3d([7, 9], [8, 10], [5, 6], \n np.array([[1, 3, 5], [2, 4, 6], [10, 11, 12]])) ", "meta": {"hexsha": "dea9775b630802b10c6669af46accf30611b3d20", "size": 1883, "ext": "py", "lang": "Python", "max_stars_repo_path": "NumpyTutorial/Questions on Polynomial.py", "max_stars_repo_name": "CarlosW1998/DigitalImageProcessing", "max_stars_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T19:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:54:48.000Z", "max_issues_repo_path": "NumpyTutorial/Questions on Polynomial.py", "max_issues_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_issues_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumpyTutorial/Questions on Polynomial.py", "max_forks_repo_name": "CarlosW1998/DigitalImageProcessingClass", "max_forks_repo_head_hexsha": "69365877e07b676f13487585ffdf029a243b0fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9347826087, "max_line_length": 67, "alphanum_fraction": 0.643653744, "include": true, "reason": "import numpy", "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769099458927, "lm_q2_score": 0.9273632941410886, "lm_q1q2_score": 0.9047142168954073}} {"text": "import numpy as np\nimport scipy.integrate as spi\nimport matplotlib.pyplot as plt\n\n#t is the independent variable\nP = 3. #period value\nBT=-6. #initian value of t (time begin)\nET=6. #final value of t (time end)\nFS=1000 #number of discrete values of t between BT and ET\n\n#the periodic real-valued function f(t) with period equal to P to simulate an acquired dataset\nf = lambda t: ((t % P) - (P / 2.)) ** 3\nt_range = np.linspace(BT, ET, FS) #all discrete values of t in the interval from BT and ET\ny_true = f(t_range) #the true f(t)\n\n#function that computes the complex fourier coefficients c-N,.., c0, .., cN\ndef compute_complex_fourier_coeffs_from_discrete_set(y_dataset, N): #via Riemann sum; N is up to nthHarmonic\n result = []\n T = len(y_dataset)\n t = np.arange(T)\n for n in range(-N, N+1):\n cn = (1./T) * (y_dataset * np.exp(-1j * 2 * np.pi * n * t / T)).sum()\n result.append(cn)\n return np.array(result)\n\n#function that computes the complex form Fourier series using cn coefficients\ndef fit_func_by_fourier_series_with_complex_coeffs(t, C):\n result = 0. + 0.j\n L = int((len(C) - 1) / 2)\n for n in range(-L, L+1):\n c = C[n+L]\n result += c * np.exp(1j * 2. * np.pi * n * t / P)\n return result\n\nFDS=20. #number of discrete values of the dataset (that is long as a period)\nt_period = np.arange(0, P, 1/FDS)\ny_dataset = f(t_period) #generation of discrete dataset\n\nmaxN=8\nCOLs = 2 #cols of plt\nROWs = 1 + (maxN-1) // COLs #rows of plt\nplt.rcParams['font.size'] = 8\nfig, axs = plt.subplots(ROWs, COLs)\nfig.tight_layout(rect=[0, 0, 1, 0.95], pad=3.0)\nfig.suptitle('simulated dataset with period P=' + str(P))\n\n#plot, in the range from BT to ET, the true f(t) in blue and the approximation in red\nfor N in range(1, maxN + 1):\n C = compute_complex_fourier_coeffs_from_discrete_set(y_dataset, N)\n #C contains the list of cn complex coefficients for n in 1..N interval.\n\n y_approx = fit_func_by_fourier_series_with_complex_coeffs(t_range, C) #y_approx contains the discrete values of approximation obtained by the Fourier series\n #y_approx contains the discrete values of approximation obtained by the Fourier series\n\n row = (N-1) // COLs\n col = (N-1) % COLs\n axs[row, col].set_title('case N=' + str(N))\n axs[row, col].scatter(t_range, y_true, color='blue', s=1, marker='.')\n axs[row, col].scatter(t_range, y_approx, color='red', s=2, marker='.')\nplt.show()\n", "meta": {"hexsha": "6f753aba46208fc4e880065d993d5c25205a9273", "size": 2433, "ext": "py", "lang": "Python", "max_stars_repo_path": "demos/python/fourier-series/fourier-series-discrete-set-using-definition-with-complex-coeffs.py", "max_stars_repo_name": "ettoremessina/function-fitting", "max_stars_repo_head_hexsha": "6abf711a2f004b81614720e66cf66f35b4c14955", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/python/fourier-series/fourier-series-discrete-set-using-definition-with-complex-coeffs.py", "max_issues_repo_name": "ettoremessina/function-fitting", "max_issues_repo_head_hexsha": "6abf711a2f004b81614720e66cf66f35b4c14955", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/python/fourier-series/fourier-series-discrete-set-using-definition-with-complex-coeffs.py", "max_forks_repo_name": "ettoremessina/function-fitting", "max_forks_repo_head_hexsha": "6abf711a2f004b81614720e66cf66f35b4c14955", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8852459016, "max_line_length": 160, "alphanum_fraction": 0.6798191533, "include": true, "reason": "import numpy,import scipy", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.976669234586964, "lm_q2_score": 0.9263037318197961, "lm_q1q2_score": 0.9046923567514886}} {"text": "import numpy as np \nimport matplotlib.pyplot as plt \nimport math \n \ndef rmse(x,y):\n # number of observations/points \n n = np.size(x) \n \n # mean of x and y vector \n m_x, m_y = np.mean(x), np.mean(y) \n\n # SS_{xx} = \\sum_{i=1}^{n} (x_i-\\bar{x})^2 = \\sum_{i=1}^{n}x_i^2 - n(\\bar{x})^2 \n SS_xx = np.sum(x*x) - n*m_x*m_x\n\n SS_yy = np.sum(y*y) - n*m_y*m_y\n\n # SS_{xy} = \\sum_{i=1}^{n} (x_i-\\bar{x})(y_i-\\bar{y}) = \\sum_{i=1}^{n} y_ix_i - n\\bar{x}\\bar{y} \n SS_xy = np.sum(y*x) - n*m_y*m_x\n\n stdx=math.sqrt(SS_xx/n)\n stdy=math.sqrt(SS_yy/n)\n\n rmse=(1/n)*(SS_xy)/(stdx*stdy)\n \n print(\"The RMSE of the linear regression model is :\",rmse)\n \n if(0.2 '2015-12-31']\n\nearly.mean()\n\nlate.mean()\n\nfrom scipy import stats\nstats.ttest_ind?\n\nstats.ttest_ind(early['assignment1_grade'], late['assignment1_grade'])\n\nstats.ttest_ind(early['assignment2_grade'], late['assignment2_grade'])\n\nstats.ttest_ind(early['assignment3_grade'], late['assignment3_grade'])", "meta": {"hexsha": "82e9d12b07897f4af449eb7e6367c29c879bc2f3", "size": 1801, "ext": "py", "lang": "Python", "max_stars_repo_path": "book/_build/jupyter_execute/pandas/Week 4-Introduction to Data Science[Coursera].py", "max_stars_repo_name": "hossainlab/dsnotes", "max_stars_repo_head_hexsha": "fee64e157f45724bba1f49ad1b186dcaaf1e6c02", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "book/_build/jupyter_execute/pandas/Week 4-Introduction to Data Science[Coursera].py", "max_issues_repo_name": "hossainlab/dsnotes", "max_issues_repo_head_hexsha": "fee64e157f45724bba1f49ad1b186dcaaf1e6c02", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book/_build/jupyter_execute/pandas/Week 4-Introduction to Data Science[Coursera].py", "max_forks_repo_name": "hossainlab/dsnotes", "max_forks_repo_head_hexsha": "fee64e157f45724bba1f49ad1b186dcaaf1e6c02", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7974683544, "max_line_length": 85, "alphanum_fraction": 0.7406996113, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.9353465179516445, "lm_q1q2_score": 0.9043996623809734}} {"text": "from math import pi\n\nimport numpy as np\n\n\ndef cylinderArea(r: float, h: float):\n \"\"\"\n Computes the total area of a cylinder\n\n :param r: cylinder base radius\n :param h: cylinder height\n\n :return: cylinder area\n :rtype: float\n \"\"\"\n\n if r > 0 and h > 0:\n return pi * pow(r, 2) * 2 + 2 * pi * r * h\n else:\n return np.nan\n\n\ndef fibonacci(n: int):\n \"\"\"\n Computes the first n Fibonacci's sequence elements\n\n Parameters:\n :param n: the amount of elements\n\n :return: n first Fibonacci's sequence elements\n :rtype: np.ndarray\n \"\"\"\n\n if n <= 0 or isinstance(n, float):\n return None\n else:\n arr = np.ndarray(shape=(1, n), dtype=int)\n\n for i in range(0, n):\n if i == 0 or i == 1:\n arr[0][i] = 1\n else:\n arr[0][i] = arr[0][i - 1] + arr[0][i - 2]\n\n return arr\n", "meta": {"hexsha": "1cf87ddf58b07b167157720f72d15f6e97a1236c", "size": 893, "ext": "py", "lang": "Python", "max_stars_repo_path": "mnultitool/misc/rigid.py", "max_stars_repo_name": "artus9033/MNultitool", "max_stars_repo_head_hexsha": "6facfcef5b1e7e7fef67adaca375bf65cbff19f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-27T13:17:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T20:42:01.000Z", "max_issues_repo_path": "mnultitool/misc/rigid.py", "max_issues_repo_name": "artus9033/MNultitool", "max_issues_repo_head_hexsha": "6facfcef5b1e7e7fef67adaca375bf65cbff19f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mnultitool/misc/rigid.py", "max_forks_repo_name": "artus9033/MNultitool", "max_forks_repo_head_hexsha": "6facfcef5b1e7e7fef67adaca375bf65cbff19f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4130434783, "max_line_length": 57, "alphanum_fraction": 0.5263157895, "include": true, "reason": "import numpy", "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9833429595026213, "lm_q2_score": 0.9196425223682085, "lm_q1q2_score": 0.9043239996300098}} {"text": "import matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nimport scipy.stats\nimport time\nfrom mls import plot_rosenbrock, plot_posterior\n#- Optimization\n\n#- Derivatives\n#- 1. by hand\n\ndef f(x):\n return np.cos(np.exp(x)) / x ** 2\n\ndef fp(x):\n return -2 * np.cos(np.exp(x)) / x ** 3 - np.exp(x) * np.sin(np.exp(x)) / x ** 2\n\nx = np.linspace(1, 3, 50)\nplt.plot(x, f(x), label='$f(x)$')\nplt.plot(x, fp(x), '.-', lw=1, label='$f\\'(x)$')\nplt.legend();\nplt.show()\n\n#- 2. numerically : finite difference\nfp_numeric=np.gradient(f(x),x)\nplt.plot(x, (fp_numeric - fp(x)), '.-', lw=1, label='absolute error')\nplt.plot(x, (fp_numeric - fp(x)) / fp(x), '.', label='relative error')\nplt.legend();\nplt.show()\n\n#- 3. Automatic Differentiation\nfrom autograd import grad, elementwise_grad\nimport autograd.numpy as anp\n\ndef f_auto(x):\n return anp.cos(anp.exp(x)) / x ** 2\n\nfp_auto = elementwise_grad(f_auto)\nplt.plot(x, fp_auto(x) - fp(x), '.-', lw=1);\nplt.show()\n\ndef sinc(x):\n return anp.sin(x) / x if x != 0 else 1.\n\n#- methods\ndef rosenbrock(x):\n x0, x1 = x\n return (1 - x0) ** 2 + 100.0 * (x1 - x0 ** 2) ** 2\nplot_rosenbrock()\nplt.show()\n\n#- rosenbrock is not a convex function\nx0 = np.linspace(-1.5, 1.5, 100)\nplt.plot(x0, rosenbrock([x0, 1.0]))\nplt.show()\n\n#- scipy optimize\nopt = minimize(rosenbrock, [-1, 0], method='Nelder-Mead', tol=1e-4)\nprint(opt.message, opt.x)\n\n#- using jacobian\nrosenbrock_grad = grad(rosenbrock)\nopt = minimize(rosenbrock, [-1, 0], method='CG', jac=rosenbrock_grad, tol=1e-4)\nprint(opt.message, opt.x)\n\n\n#- see the optimization develop\ndef optimize_rosenbrock(method, use_grad=False, x0=-1, y0=0, tol=1e-4):\n \n all_calls = []\n def rosenbrock_wrapped(x):\n all_calls.append(x)\n return rosenbrock(x)\n \n path = [(x0,y0)]\n def track(x):\n path.append(x)\n\n jac = rosenbrock_grad if use_grad else False\n \n start = time.time()\n opt = minimize(rosenbrock_wrapped, [x0, y0], method=method, jac=jac, tol=tol, callback=track)\n stop = time.time()\n \n assert opt.nfev == len(all_calls)\n njev = opt.get('njev', 0) \n print('Error is ({:+.2g},{:+.2g}) after {} iterations making {}+{} calls in {:.2f} ms.'\n .format(*(opt.x - np.ones(2)), opt.nit, opt.nfev, njev, 1e3 * (stop - start))) \n\n xrange, yrange = plot_rosenbrock(path=path, all_calls=all_calls)\n\noptimize_rosenbrock(method='Nelder-Mead', use_grad=False)\nplt.show()\n\n#- Can use different methods: Nelder-Mead, CG, Newton-CG, Powell, BFGS\n#- initial point can have big effect on optimization cost\n\ndef cost_map(method, tol=1e-4, ngrid=50):\n xrange, yrange = plot_rosenbrock(shaded=False)\n x0_vec = np.linspace(*xrange, ngrid)\n y0_vec = np.linspace(*yrange, ngrid)\n cost = np.empty((ngrid, ngrid))\n for i, x0 in enumerate(x0_vec):\n for j, y0 in enumerate(y0_vec):\n opt = minimize(rosenbrock, [x0, y0], method=method, tol=tol)\n cost[j, i] = opt.nfev\n plt.imshow(cost, origin='lower', extent=[*xrange, *yrange],\n interpolation='none', cmap='magma', aspect='auto', vmin=0, vmax=250)\n plt.colorbar().set_label('Number of calls')\n\ncost_map('Nelder-Mead')\nplt.show()\n\ncost_map('BFGS')\nplt.show()\n\n#- stochastic optimization: loops on data\nD = scipy.stats.norm.rvs(loc=0, scale=1, size=200, random_state=123)\nx = np.linspace(-4, +4, 100)\nplt.hist(D, range=(x[0], x[-1]), bins=20, normed=True)\nplt.plot(x, scipy.stats.norm.pdf(x,loc=0,scale=1))\nplt.xlim(x[0], x[-1]);\nplt.show()\n\n#- likelihood\ndef NLL(theta, D):\n mu, sigma = theta\n return anp.sum(0.5 * (D - mu) ** 2 / sigma ** 2 + 0.5 * anp.log(2 * anp.pi) + anp.log(sigma))\n\n#-priors\ndef NLP(theta):\n mu, sigma = theta\n return -anp.log(sigma) if sigma > 0 else -anp.inf\n\n#- posterior\ndef NLpost(theta, D):\n return NLL(theta, D) + NLP(theta)\n\nplot_posterior(D);\nplt.show()\n\n#- Optimization with gradient decent\nNLpost_grad = grad(NLpost)\n\n#-step\ndef step(theta, D, eta):\n return theta - eta * NLpost_grad(theta, D) / len(D)\n\ndef GradientDescent(mu0, sigma0, eta, n_steps):\n path = [np.array([mu0, sigma0])]\n for i in range(n_steps):\n path.append(step(path[-1], D, eta))\n return path\n\nplot_posterior(D, path=GradientDescent(mu0=-0.2, sigma0=1.3, eta=0.2, n_steps=15));\nplt.show()\n\n#- Stochastic Gradient Descent\ndef StochasticGradientDescent(mu0, sigma0, eta, n_minibatch, eta_factor=0.95, seed=123, n_steps=15):\n gen = np.random.RandomState(seed=seed)\n path = [np.array([mu0, sigma0])]\n for i in range(n_steps):\n minibatch = gen.choice(D, n_minibatch, replace=False)\n path.append(step(path[-1], minibatch, eta))\n eta *= eta_factor\n return path\n\nplot_posterior(D, path=StochasticGradientDescent(\n mu0=-0.2, sigma0=1.3, eta=0.2, n_minibatch=100, n_steps=100));\nplt.show()\n\n#- with no decay of learning rate\nplot_posterior(D, path=StochasticGradientDescent(\n mu0=-0.2, sigma0=1.3, eta=0.2, eta_factor=1, n_minibatch=100, n_steps=100))\n\n#- smaller minibatch\nplot_posterior(D, path=StochasticGradientDescent(\n mu0=-0.2, sigma0=1.3, eta=0.15, eta_factor=0.97, n_minibatch=20, n_steps=75))\n\n\n", "meta": {"hexsha": "a6abdff5ba6b1cc17862cdd141da2df766baa181", "size": 5204, "ext": "py", "lang": "Python", "max_stars_repo_path": "projects/py/projects/optimize.py", "max_stars_repo_name": "gdhungana/project_mis", "max_stars_repo_head_hexsha": "dfd9612a05fb07237387d98597f73ba6014bf9d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/py/projects/optimize.py", "max_issues_repo_name": "gdhungana/project_mis", "max_issues_repo_head_hexsha": "dfd9612a05fb07237387d98597f73ba6014bf9d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/py/projects/optimize.py", "max_forks_repo_name": "gdhungana/project_mis", "max_forks_repo_head_hexsha": "dfd9612a05fb07237387d98597f73ba6014bf9d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4371584699, "max_line_length": 100, "alphanum_fraction": 0.650076864, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128327, "lm_q2_score": 0.9324533074525657, "lm_q1q2_score": 0.9042796133654444}} {"text": "# -*- coding:UTF8 -*-\nimport numpy as np\nimport sys,os\nimport math\n\nfrom tools.loadData import load_array\nfrom tools import ulti\n\npath = os.getcwd()\n\n\ndef Schmidt_procedure(mat, m, n):\n # mat_B = mat.copy()\n Q = np.zeros((m,n))\n R = np.zeros((n,n))\n for col in range(n):\n curr_col = mat[:,col]\n # print(math.sqrt(np.sum(np.square(curr_col))))\n if col == 0:\n R[0,col] = math.sqrt(np.sum(np.square(curr_col)))\n q = curr_col / R[0,col]\n Q[:,col] = q.copy()\n else:\n q = curr_col.copy()\n for j in range(col):\n R[j,col] = np.matmul(Q[:, j], mat[:, col])\n \n for k in range(col):\n q -= R[k,col] * Q[:, k]\n R[col,col] = math.sqrt(np.sum(np.square(q)))\n q = q/ R[col,col]\n Q[:,col] = q.copy()\n return Q,R\n\nif __name__ == \"__main__\":\n input_file=path+'/data/example2.txt'\n # output_file=''\n matrix, m, n = load_array(input_file,\"QR\")\n ulti.print_array(matrix, m, n )\n if matrix.size ==0:\n print(\"input Error!\")\n sys.exit()\n # 首先判断矩阵是否是列线性无关的\n mat_rank = ulti.rank_of_matrix(matrix,m,n)\n if mat_rank>> calculate_findiff_coefs([-2, -1, 0, 1, 2], 4) \n array([ 1., -4., 6., -4., 1.])\n \n >>> calculate_findiff_coefs([-2, -1, 0, 1, 2, 1.99], 3)\n array([ -0.1867, -0.6722, 3.7688, -6.0505, -124.5 , 127.6406])\n \n References\n ----------\n https://web.media.mit.edu/~crtaylor/calculator.html\n https://github.com/maroba/findiff/blob/e8ca33707e3e25d76bf0f93b2391e466209287b1/findiff/coefs.py\n \"\"\"\n \n if len(offsets) < deriv + 1:\n raise ValueError(\"Length of offsets should be larger than derivative order plus 1.\")\n if len(offsets) != len(set(offsets)):\n # Note that this program could not handle pathological cases, only make simple check instead.\n raise ValueError(\"Possibly exactly same offset value is given. Please check `offsets'.\")\n \n offsets = np.asarray(offsets)\n matrix = np.array([offsets**n for n in range(len(offsets))])\n rhs = np.zeros(len(offsets))\n rhs[deriv] = np.math.factorial(deriv)\n \n return np.linalg.solve(matrix, rhs)\n\n\ndef calculate_GRR_trig(offsets_half, deriv, fx_pos, fx_neg, f0=None):\n \"\"\"\n Calculate (Generalized) Rutishauser–Romberg Triangle\n \n Parameters\n ----------\n offsets_half : array_like\n Positive half part of offsets. For example, if all offsets are [-2, -1, 0, 1, 2],\n then `offsets_half' should be [1, 2].\n Must be a geometric sequence. This function does not make double check on this.\n Do not contain zero in this array.\n deriv : int\n fx_pos : array_like\n Value list of f(offsets_half). Dimension should be the same to `offsets_half'.\n fx_neg : array_like\n Value list of f(-offsets_half). Dimension should be the same to `offsets_half'.\n f0 : float or None\n Value of f(0). May leave as None if derivative order is odd number.\n \n Returns\n -------\n grr_trig : ndarray\n (Generalized) Rutishauser–Romberg triangle.\n \"\"\"\n \n if deriv % 2 == 0 and f0 is None:\n raise ValueError(\"`f0' should be provided if derivative order is even number.\")\n else:\n f0 = 0 if f0 is None else f0\n if len(offsets_half) < 2:\n raise ValueError(\"length of `offsets_half' must >= 2 in order to calculate ratio.\")\n\n comp_len = (deriv + 1) // 2\n mat_size = len(offsets_half) - comp_len\n grr_trig = np.zeros((mat_size, mat_size))\n ratio = offsets_half[-1] / offsets_half[-2]\n \n for r in range(mat_size):\n i_end = r + comp_len\n offsets = np.concatenate([offsets_half[r:i_end], -offsets_half[r:i_end], [0]])\n coef_list = calculate_findiff_coefs(offsets, deriv)\n val_list = np.concatenate([fx_pos[r:i_end], fx_neg[r:i_end], [f0]])\n grr_trig[r, 0] = (coef_list * val_list).sum()\n for c in range(1, mat_size):\n for r in range(mat_size-c):\n grr_trig[r, c] = (ratio**(2*c) * grr_trig[r, c-1] - grr_trig[r+1, c-1]) / (ratio**(2*c) - 1) \n \n for r in range(mat_size):\n for c in range(mat_size-r, mat_size):\n grr_trig[r, c] = np.nan\n return grr_trig\n\n\ndef calculate_GRR_trig_with_f(offsets_half, deriv, f):\n \"\"\"\n Calculate (Generalized) Rutishauser–Romberg Triangle with Given Function\n \n Parameters\n ----------\n offsets_half : array_like\n deriv : int\n f : function\n Should be able to handle both array_like and float input.\n \n Returns\n -------\n grr_trig : ndarray\n (Generalized) Rutishauser–Romberg triangle.\n \"\"\"\n \n fx_pos = [f(o) for o in offsets_half]\n fx_neg = [f(-o) for o in offsets_half]\n f0 = f(0)\n return calculate_GRR_trig(offsets_half, deriv, fx_pos, fx_neg, f0)\n\n\ndef check_grr_trig_converge(grr_trig):\n \"\"\"\n Convergence Check Matrix of (Generalized) Rutishauser–Romberg Triangle\n \n Parameters\n ----------\n grr_trig : ndarray\n (Generalized) Rutishauser–Romberg triangle.\n \n Return\n ------\n mat_chk : ndarray\n \"\"\"\n \n n = len(grr_trig)\n mat_chk = np.zeros((n, n))\n for r in range(0, n-1):\n for c in range(1, n-r-1):\n mat_chk[r, c] = np.abs(grr_trig[r, c] - grr_trig[r+1, c]) + np.abs(grr_trig[r, c] - grr_trig[r, c-1])\n for r in range(n):\n mat_chk[r, 0] = np.nan\n for r in range(0, n):\n for c in range(n-r-1, n):\n mat_chk[r, c] = np.nan\n return mat_chk\n\n\ndef output_pd_grr_trig(offsets_half, grr_trig, tolerance=3):\n \"\"\"\n Pandas Presentation of (Generalized) Rutishauser–Romberg Triangle\n \n Parameters\n ----------\n offsets_half : array_like\n grr_trig : ndarray\n (Generalized) Rutishauser–Romberg triangle.\n tolerance : int\n Number of minimum difference cells in convergence check matrix.\n \n Return\n ------\n df : pandas.io.formats.style.Styler\n Pandas show of GRR triangle.\n df_check : pandas.io.formats.style.Styler\n Pandas show of convergence check matrix of GRR triangle.\n \"\"\"\n n = len(grr_trig)\n df = pd.DataFrame(grr_trig, columns=range(n), index=offsets_half[:n])\n df_check = pd.DataFrame(check_grr_trig_converge(grr_trig), columns=range(n), index=offsets_half[:n])\n df.replace(np.nan, \"\", regex=True, inplace=True)\n df_check.replace(np.nan, \"\", regex=True, inplace=True)\n\n t = check_grr_trig_converge(grr_trig).flatten()\n t = t.argsort()[:3]\n t = np.array([t // n, t % n]).T\n \n def highlight_cells(x):\n df = x.copy()\n df.loc[:,:] = '' \n for r, c in t:\n df.iloc[r, c] = \"background-color: lightgreen\"\n df.iloc[r, c-1] = \"background-color: lightgreen\"\n df.iloc[r+1, c] = \"background-color: lightgreen\"\n return df\n\n df = df.style.apply(highlight_cells, axis=None)\n df_check = df_check.style.apply(highlight_cells, axis=None)\n return df, df_check\n", "meta": {"hexsha": "428d43c19cf3c641b68d0c90974d4c880b341a44", "size": 6152, "ext": "py", "lang": "Python", "max_stars_repo_path": "source/Simple_Notes/grrtrig.py", "max_stars_repo_name": "ajz34/ajz34.readthedocs.io", "max_stars_repo_head_hexsha": "73be05a73241c18b98fd0d4dbdc48c643278c3da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-30T12:31:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T03:56:56.000Z", "max_issues_repo_path": "source/Simple_Notes/grrtrig.py", "max_issues_repo_name": "ajz34/ajz34.readthedocs.io", "max_issues_repo_head_hexsha": "73be05a73241c18b98fd0d4dbdc48c643278c3da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Simple_Notes/grrtrig.py", "max_forks_repo_name": "ajz34/ajz34.readthedocs.io", "max_forks_repo_head_hexsha": "73be05a73241c18b98fd0d4dbdc48c643278c3da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-30T12:32:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T12:32:09.000Z", "avg_line_length": 32.2094240838, "max_line_length": 113, "alphanum_fraction": 0.6115084525, "include": true, "reason": "import numpy", "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992942089574, "lm_q2_score": 0.9334308133443092, "lm_q1q2_score": 0.9034670254288499}} {"text": "# Bite Size Bayes\n\nCopyright 2020 Allen B. Downey\n\nLicense: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n## Estimating the difference between proportions\n\nFrom [the Reddit statistics forum](https://www.reddit.com/r/statistics/comments/fsieqf/q_distribution_of_difference_of_correlated_coin/)\n\n> You have two coins, and a sequence of flips from each. Your goal is to assess the distribution of the difference in coin flips. You could do Bayesian updating with a Beta prior to get a posterior for each coin, and assuming independence take the convolution. If you had the additional information that the average of the coin probabilities was p, how would you incorporate it? Is there any way to avoid the convolution and build a prior on the difference in coin flip probabilities directly? Thanks!\n\nI suggested:\n\n> Suppose the probability of heads for the two coins is p+x and p-x. If we know p, all we have to estimate is x.\n>\n>The likelihood function is the product of two binomials.\n>\n>I would use a grid method to estimate the posterior.\n\nHere's how:\n\nxs = np.arange(101) / 100\nuniform = pd.Series(1, index=xs)\nuniform /= uniform.sum()\n\nWe can use `binom.pmf` to compute the likelihood of the data for each possible value of $x$.\n\nfrom scipy.stats import binom\n\ndef compute_likelihood(xs, p_avg, k, n):\n p_low = p_avg - xs\n p_high = p_avg + xs\n\n likelihood = (binom.pmf(k, n, p=p_low) + \n binom.pmf(k, n, p=p_high)) /2\n likelihood = np.nan_to_num(likelihood)\n \n return likelihood\n\nxs = uniform.index\np_avg = 0.5\nk = 75\nn = 100\nlikelihood1 = compute_likelihood(xs, p_avg, k, n)\n\nplt.plot(likelihood1)\nplt.xlabel('x')\nplt.title('Likelihood 1');\n\nxs = uniform.index\np_avg = 0.5\nk = 25\nn = 100\nlikelihood2 = compute_likelihood(xs, p_avg, k, n)\n\nplt.plot(likelihood2)\nplt.xlabel('x')\nplt.title('Likelihood 2');\n\nNow we can do the Bayesian update in the usual way, multiplying the priors and likelihoods:\n\nposterior = uniform * likelihood1 * likelihood2\n\nComputing the total probability of the data:\n\ntotal = posterior.sum()\ntotal\n\nAnd normalizing the posterior.\n\nposterior /= total\n\nHere's what it looks like.\n\nposterior.plot()\n\nplt.xlabel('Probability of heads (x)')\nplt.ylabel('Probability')\nplt.title('Posterior distribution, uniform prior');\n\nThe posterior mean is pretty close to the value I used to construct the data, 0.25.\n\ndef pmf_mean(pmf):\n \"\"\"Compute the mean of a PMF.\n \n pmf: Series representing a PMF\n \n return: float\n \"\"\"\n return np.sum(pmf.index * pmf)\n\npmf_mean(posterior)\n\n", "meta": {"hexsha": "397bf23d1c16778979f15b46347624036ec1eb39", "size": 2699, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/difference.py", "max_stars_repo_name": "myamullaciencia/Bayesian-statistics", "max_stars_repo_head_hexsha": "1439716e377884465316cf9512f8e3a9199e79d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/difference.py", "max_issues_repo_name": "myamullaciencia/Bayesian-statistics", "max_issues_repo_head_hexsha": "1439716e377884465316cf9512f8e3a9199e79d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/difference.py", "max_forks_repo_name": "myamullaciencia/Bayesian-statistics", "max_forks_repo_head_hexsha": "1439716e377884465316cf9512f8e3a9199e79d6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2626262626, "max_line_length": 501, "alphanum_fraction": 0.7347165617, "include": true, "reason": "import numpy,from scipy", "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141546, "lm_q2_score": 0.935346504885345, "lm_q1q2_score": 0.9034507945528384}} {"text": "#Runge Kutta Fourth (4) Order Method\nimport numpy as np \n\ndef dy(x,y):\n dyvalue = x*y + y**2\n return dyvalue\n #Note: change the derivative function based on question!!!!!! Example: y-x\n\ny0 = 1 # input y for xo\nx = 0\nh = 0.1\ny = y0\nfinalx = 0.3\ninterval = finalx - x\nn = interval/h\ni = 0\n\n\n\nwhile i<=n:\n print(\"_________________\" + str(i)+ \"_________________\"+\"\\n\")\n k1 = dy(x,y) *h\n print(\"k1= \"+str(k1))\n k2 = dy(x+h*0.5,y+k1*0.5) *h\n print(\"k2= \"+str(k2))\n k3 = dy(x+h*0.5,y+k2*0.5) *h\n print(\"k3= \"+str(k3))\n k4 = dy(x+h,y+k3) *h\n print(\"k4= \"+str(k4))\n y = y + (k1+2*k2+2*k3+k4)/6\n x = x+h\n i+=1\n print(\"\\n\")\n print(\"y = \" + str(y))\n print(\"\\n\")\n print(\"x = \" + str(x))\n print(\"\\n\")\n", "meta": {"hexsha": "827b97947492c9d83b9e35484e91822e1902da01", "size": 753, "ext": "py", "lang": "Python", "max_stars_repo_path": "4runge kutta method.py", "max_stars_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_stars_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4runge kutta method.py", "max_issues_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_issues_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4runge kutta method.py", "max_forks_repo_name": "pramotharun/Numerical-Methods-with-Python", "max_forks_repo_head_hexsha": "bd5676bcc4ac5defd13608728df2387b5fdcdfcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8157894737, "max_line_length": 76, "alphanum_fraction": 0.5126162019, "include": true, "reason": "import numpy", "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668717616667, "lm_q2_score": 0.9207896818685504, "lm_q1q2_score": 0.9034483317093859}} {"text": "# -*- coding: utf-8 -*-\n\nimport numpy as np \nimport scipy.optimize as opt\nimport matplotlib.pyplot as plt \n\n\n \n#poly function.\ndef poly_func(w, x):\n f = np.poly1d(w)\n return f(x)\n \n\n#sin(x)\ndef sin_func(x):\n return np.sin(x)\n\n#calculate the error between estimation and the groudtruth.\ndef err_func(w, y, x):\n return y - poly_func(w, x)\n\n#regulization\ndef reg_err_func(w, y, x):\n reg_err = y - poly_func(w, x)\n reg_err = np.append(reg_err, np.sqrt(np.e**(1/9)) * w)\n return reg_err\n \n#plot\ndef show(n,m,Regularization):\n x = np.linspace(0, 2*np.pi, n) #equal difference pick up point according to the sample amount. \n y0 = sin_func(x)\n y1 = [np.random.normal(0, 0.1) + y for y in y0] #add guassian noise\n ''' polyfit: x, y, degree; the w is the coefficient.'''\n w = np.polyfit(x,y1,m)\n if not Regularization : \n plsq = opt.leastsq(err_func, w, args=(y1, x))\n else: \n plsq = opt.leastsq(reg_err_func, w, args=(y1, x))\n # plt.figure(figsize = (6,4)) \n plt.figure()\n plt.plot(np.linspace(0, 2*np.pi, 100), sin_func(np.linspace(0, 2*np.pi, 100)), 'g-', label='sin(x)')\n plt.plot(np.linspace(0, 2*np.pi, 100), poly_func(plsq[0], np.linspace(0, 2*np.pi, 100)), 'r', label='fitted curve')\n plt.plot(x, y1, 'bo', label='noise point')\n plt.xlabel('x')\n plt.ylabel('t')\n plt.xlim(-0.2,2*np.pi + 0.2)\n plt.ylim(-1.4,1.4)\n plt.legend()\n if not Regularization:\n title = \"degree=\" + str(m) + \" sample=\" + str(n)\n plt.title(title)\n plt.savefig(\"degree=\" + str(m) + \" sample=\" + str(n) + \".png\")\n else:\n title = \"degree=\" + str(m) + \" sample = \" + str(n) + \" with regularization term\"\n plt.title(title)\n plt.savefig(\"degree=\" + str(m) + \" sample=\" + str(n) + \" with regularization term.png\") \n print title + \" done! regularization:\" + str(Regularization) \n # plt.show() \n\n \n\nif __name__ == '__main__':\n print 'start homework 1...'\n show(10,3,False)# fit degree 3 curve in 10 samples\n show(10,9,False)# fit degree 9 curve in 10 samples\n show(15,9,False)# fit degree 9 curve in 15 samples\n show(100,9,False)# fit degree 9 curve in 100 samples\n show(10,9,True)# fit degree 9 curve in 10 samples but with regularization term\n", "meta": {"hexsha": "abb14a4d8b732e2b2dee7da1012ad1ff87456ecf", "size": 2279, "ext": "py", "lang": "Python", "max_stars_repo_path": "Hw1_Curve_Fitting/polynomial_curve_fitting.py", "max_stars_repo_name": "desword/CS_Math", "max_stars_repo_head_hexsha": "1ec4c4e415b92e90e8ca2d12cc894c6da997a05e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hw1_Curve_Fitting/polynomial_curve_fitting.py", "max_issues_repo_name": "desword/CS_Math", "max_issues_repo_head_hexsha": "1ec4c4e415b92e90e8ca2d12cc894c6da997a05e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hw1_Curve_Fitting/polynomial_curve_fitting.py", "max_forks_repo_name": "desword/CS_Math", "max_forks_repo_head_hexsha": "1ec4c4e415b92e90e8ca2d12cc894c6da997a05e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5571428571, "max_line_length": 119, "alphanum_fraction": 0.6042123738, "include": true, "reason": "import numpy,import scipy", "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.9324533036984185, "lm_q1q2_score": 0.9034131351879301}} {"text": "'''\r\n\r\nVector Norm - Finding length of vector\r\n\r\nMany ways to find length of the vector:\r\n\r\n1. L1 Norm - Lasso regression (a.k.a Taxicab Norm or Manhattan Norm)\r\n2. L2 Norm - Ridge regression (a.k.a Eucledian Norm)\r\n3. p Norm\r\n4. Vector Max Norm\r\n\r\nNorm Equation: https://image.slidesharecdn.com/02linearalgebra-171229202748/95/02-linear-algebra-15-638.jpg?cb=1514579308\r\n\r\n'''\r\n\r\n'''\r\n\r\nhow to find length of a vector ?\r\n- draw a triangle to the vector and apply pythagoras theorem i,e sqrt of a2 + b2 = c\r\n\r\nwhat if vector is in 3D ?\r\n- sqrt of a2 + b2 + c2 = d\r\n\r\nthis process of knowing the length of vector is known as L2 Norm.\r\n\r\n'''\r\n\r\n# L2 norm implementation\r\nimport numpy as np\r\nx = np.array([2,3,4])\r\ny = np.array([3,4])\r\n\r\n# length of vector y can be found using \r\n# norm function using linear algebra module\r\nfrom numpy.linalg import norm\r\nlength_of_y = norm(y) # by default L2 form\r\n# print length_of_y --> 5.0\r\n\r\n# length of vector y can be found using \r\n# norm function using linear algebra module\r\nlength_of_x = norm(x) # by default L2 form\r\n# print length_of_x --> 5.385164807134504\r\n\r\n# lets verify length of vector x by manually calculating:\r\nnp.sqrt((4+9+16))\r\n# 5.385164807134504\r\n\r\n# L2 Norm of the vector i,e Ridge regression is used for regularization technique in Machine learning\r\n\r\n'''\r\nL1 Norm\r\n\r\nvector --> [-1,2,3,-4]\r\n\r\ntake absolute value of each component and summazation i,e\r\n\r\n1 + 2 + 3 + 4 = 10, is known as L1 Norm\r\n\r\n'''\r\n\r\n# L1 norm implementation\r\n \r\nx = np.array([-1,2,3,-4])\r\n\r\nl1_norm = norm(x,ord = 1) # ord = 1 --> find L1 norm of the vector\r\n# print l1_norm --> 10.0\r\n\r\n'''\r\np norm\r\n\r\n- generalized form\r\n- p = 2 , L2 norm\r\n- p = 1, L1 norm\r\n\r\n'''\r\n\r\n# p norm implementation\r\n\r\nz = np.array([-1,2,3,-4])\r\n#p=1\r\np1 = norm(z,1)\r\n# print p1 --> 10.0\r\n\r\n#p=2\r\np2 = norm(z,2)\r\n# print p2 --> 5.477225575051661\r\n\r\n#p=3\r\np3 = norm(z,3) # take cube on each component, summation & take cube root of sum\r\n# print p3 --> 4.641588833612778\r\n\r\n# in summary, based on p value, squaring and root varies\r\n\r\n'''\r\nVector Max Norm\r\n\r\n- return max value in vector\r\n'''\r\n\r\n# implementation of vector max norm\r\n\r\nx = np.random.randint(0,1000,10)\r\n# x --> array([357, 460, 303, 200, 845, 617, 69, 870, 818, 840])\r\n\r\n# we can use np.max but crux is how can we use/prove with the norm equation\r\n# we get vector max norm when p = infinity\r\nfrom math import inf\r\nmax_norm = norm(x,ord=inf)\r\n# max_norm --> 870.0\r\n\r\n'''\r\nSUMMARY:\r\n\r\n- L1 norm can be calculated by sum of absolute values of the vector\r\n- L2 norm can be calculated by square root of the sum of the squared vector values\r\n- Max norm can be calculated by finding maximum vector value\r\n\r\n'''\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7de071d8c9833459cad357b6d41b90ceaca29cee", "size": 2681, "ext": "py", "lang": "Python", "max_stars_repo_path": "vector/vector_norm.py", "max_stars_repo_name": "Akshaykumarcp/linear_algebra", "max_stars_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-06T12:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:31:53.000Z", "max_issues_repo_path": "vector/vector_norm.py", "max_issues_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_issues_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vector/vector_norm.py", "max_forks_repo_name": "Akshaykumarcp/practical_linear_algebra", "max_forks_repo_head_hexsha": "083f1d8d77b944d9b8e85eb34c65b87794a9b6ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9754098361, "max_line_length": 122, "alphanum_fraction": 0.6609474077, "include": true, "reason": "import numpy,from numpy", "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9845754456551737, "lm_q2_score": 0.9173026573249612, "lm_q1q2_score": 0.9031536726363988}} {"text": "import numpy as np\n\ndef get_largest_eigen_vectors(matrix, n=None):\n \"\"\"\n Computes the eigen vectors of 'matrix' and returns the n largest ones.\n If n is set to None, then return them all in decreasing order.\n \"\"\"\n _, n_features = matrix.shape\n if n is None:\n n = n_features\n\n assert n > 0, 'Need to select at least one eigen vector.'\n\n eigen_values, eigen_vectors = np.linalg.eig(matrix)\n idx = eigen_values.argsort()[::-1] # ordering the eigen values in decreasing order\n ordered_eigen_vectors = eigen_vectors[:,idx] # ordering the eigen vectors\n eigen_vectors = ordered_eigen_vectors[:,range(n)]\n\n return eigen_vectors\n\n\ndef get_lowest_eigen_vectors(matrix, n=None):\n \"\"\"\n Computes the eigen vectors of 'matrix' and returns the n lowest ones.\n If n is set to None, then return them all in increasing order.\n \"\"\"\n _, n_features = matrix.shape\n if n is None:\n n = n_features\n\n assert n > 0, 'Need to select at least one eigen vector.'\n\n eigen_values, eigen_vectors = np.linalg.eig(matrix)\n idx = eigen_values.argsort() # ordering the eigen values in decreasing order\n ordered_eigen_vectors = eigen_vectors[:,idx] # ordering the eigen vectors\n eigen_vectors = ordered_eigen_vectors[:,range(n)]\n\n return eigen_vectors\n\n\ndef as_column_vect(vector):\n \"\"\"\n Takes a row or a columns vector and makes sure it returns a column vector.\n \"\"\"\n try:\n nrow, ncol = vector.shape\n assert nrow == 1 or ncol == 1, 'This is not a vector'\n except ValueError: # case where we have an array instead of a matrix.\n vector = np.matrix(vector)\n nrow, ncol = vector.shape\n\n if ncol == 1:\n return vector\n return vector.T\n\n\ndef whiten_data(data):\n \"\"\"\n Returns a transformed version of 'data' such that its covariance matrix\n is equal to the identity.\n The data is assumed to be shaped such that:\n rows: the features/variables\n columns: the individuals\n \"\"\"\n covariance_matrix = data * data.T\n eig_values, eig_vectors = np.linalg.eig(covariance_matrix)\n eig_values = np.abs(eig_values) # some values are so close to 0 that they are\n # estimated as negative\n D_m12 = np.diag(1. / np.sqrt(eig_values)) # D_m12 == D^(-1/2)\n whitened_data = (eig_vectors * D_m12 * eig_vectors.T) * data\n return whitened_data\n\n\ndef center_data(data):\n \"\"\"\n Returns a transformed version of 'data' such that the column-vector of its\n mean is null.\n The data is assumed to be shaped such that:\n rows: the features/variables\n columns: the individuals\n \"\"\"\n return data - data.mean(axis=1)\n\n\ndef normalize_data(data):\n \"\"\"\n Center the datapoints and whiten them.\n \"\"\"\n centered_data = center_data(data)\n whitened_centered_data = whiten_data(centered_data)\n return whitened_centered_data\n\n\ndef filter_low_values(values, threshold=1.e-11):\n \"\"\"\n Filter low and negative values of the array 'values'.\n If a value is found to be below the threshold: normalize it by 0\n \"\"\"\n return np.array([v if v > threshold else 0 for v in values])\n", "meta": {"hexsha": "44d02db1737cf5d3ff32f40bd5f763053f422193", "size": 3150, "ext": "py", "lang": "Python", "max_stars_repo_path": "linalg_toolbox.py", "max_stars_repo_name": "RomainSabathe/cw_dimension_reduction", "max_stars_repo_head_hexsha": "fbe62e66d78ffd5dee5c6643cc03d97d7025641f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linalg_toolbox.py", "max_issues_repo_name": "RomainSabathe/cw_dimension_reduction", "max_issues_repo_head_hexsha": "fbe62e66d78ffd5dee5c6643cc03d97d7025641f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linalg_toolbox.py", "max_forks_repo_name": "RomainSabathe/cw_dimension_reduction", "max_forks_repo_head_hexsha": "fbe62e66d78ffd5dee5c6643cc03d97d7025641f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5, "max_line_length": 86, "alphanum_fraction": 0.6733333333, "include": true, "reason": "import numpy", "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.9381240147088438, "lm_q1q2_score": 0.903106764292343}} {"text": "import numpy as np\nimport matplotlib.pylab as plt\n\ndef softmax(a):\n exp_a = np.exp(a)\n return exp_a / np.sum(exp_a)\n\na = np.array([0.3, 2.9, 4.0])\nprint(softmax(a))\n\na = np.array([1010, 1000, 990])\nprint(softmax(a))\n\n#実際には値がでかいとエラーとなる\n#したがって計算結果が変わらない特質から最大の要素で分子分母全体をマイナスする\ndef softmax(a):\n exp_a = np.exp(a - np.max(a))\n return exp_a / np.sum(exp_a)\n\na = np.array([1010, 1000, 990])\ny = softmax(a)\nprint(y)\nprint(np.sum(y))\n\n#特徴は合計が1になるので確率として扱える点\n#出力層に回帰問題では恒等関数、分類問題ではソフトマックスを用いるのが通例\n", "meta": {"hexsha": "54f38f2588891e5f0b1f5baa8a6e8e6dd5c76e30", "size": 500, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/src/zero/softmax.py", "max_stars_repo_name": "d-ikeda-sakurasoft/deep-learning", "max_stars_repo_head_hexsha": "e253d11bafa34bb0260bb655268054534cc8cff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/src/zero/softmax.py", "max_issues_repo_name": "d-ikeda-sakurasoft/deep-learning", "max_issues_repo_head_hexsha": "e253d11bafa34bb0260bb655268054534cc8cff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python/src/zero/softmax.py", "max_forks_repo_name": "d-ikeda-sakurasoft/deep-learning", "max_forks_repo_head_hexsha": "e253d11bafa34bb0260bb655268054534cc8cff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5185185185, "max_line_length": 39, "alphanum_fraction": 0.694, "include": true, "reason": "import numpy", "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639686018701, "lm_q2_score": 0.9294404013696266, "lm_q1q2_score": 0.9030108049335894}} {"text": "import numpy as np\nimport helpers\n\ndef mse(y, tx, w):\n \"\"\"\n Mean squared error loss function.\n \n Parameters\n ----------\n y : Vector\n Output.\n tx : Matrix\n Input.\n w : Vector\n weights.\n \n Returns\n -------\n loss function.\n \n \"\"\"\n e = y - tx @ w\n return (1/(2*tx.shape[0])) * np.sum(e**2)\n\ndef mae(y, tx, w):\n \"\"\"\n Mean absolute error.\n\n Parameters\n ----------\n y : Vector\n Output.\n tx : Array\n Input.\n w : Vector\n Weights.\n\n Returns\n -------\n loss function.\n\n \"\"\"\n \n return np.mean(np.abs(y - tx @ w))\n\ndef logistic_error(y, tx, w):\n \"\"\" \n Logistic error\n \n Parameters\n ----------\n y : Vector\n Output.\n tx : Matrix\n Input.\n w : TYPE\n Weights.\n\n Returns\n -------\n loss : Scalar\n Loss function.\n\n \"\"\"\n a = helpers.sigmoid(tx @ w)\n loss = - (1 / tx.shape[0]) * np.sum((y * np.log(a)) + ((1 - y) * np.log(1 - a)))\n return loss\n\ndef reg_logistic_error(y, tx, w, lambda_, reg):\n \"\"\"\n Logistic error with regularization\n\n Parameters\n ----------\n y : Vector\n Output.\n tx : Matrix\n Input.\n w : Vector\n Weights.\n lambda_ : Scalar\n Constant\n reg: Scalar\n L1 or L2 regularization\n\n Returns\n -------\n loss : Scalar\n Loss function.\n\n \"\"\"\n assert (reg==1 or reg==2), \"reg needs to be 1 or 2\"\n loss = logistic_error(y, tx, w) + lambda_ * (np.linalg.norm(w, reg) ** reg)\n return loss\n", "meta": {"hexsha": "209a204400a383215dddbaad1cbd68d53859c639", "size": 1560, "ext": "py", "lang": "Python", "max_stars_repo_path": "project1/utils/costs.py", "max_stars_repo_name": "itslwg/epflml-projects", "max_stars_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project1/utils/costs.py", "max_issues_repo_name": "itslwg/epflml-projects", "max_issues_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-25T11:18:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-30T15:49:46.000Z", "max_forks_repo_path": "project1/utils/costs.py", "max_forks_repo_name": "itslwg/epflml-projects", "max_forks_repo_head_hexsha": "74180683f5f07845f93e1e45e5197dc36802d0f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.4210526316, "max_line_length": 84, "alphanum_fraction": 0.4724358974, "include": true, "reason": "import numpy", "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446418006305, "lm_q2_score": 0.9273632936392131, "lm_q1q2_score": 0.9029223018544046}} {"text": "# LIBRARIES\nfrom sympy import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# COLLOCATION METHOD\n## SYMBOLS\nx, y, C1, C2 = symbols('x y C1 C2')\n\n## THIRD ORDER POLYNOMIAL\ny_ = C1*x*(2 - x) + C2*x*(1 - x)**2 + 1*x\n\n## POLYNOMIAL DERIVATIVER\ndy_ = y_.diff(x)\nddy_ = y_.diff(x,x)\n\n## RESIDUALS\nR = -ddy_ - y_ + x**2 \n\n## EQUATION SYSTEMS\nR1 = R.subs(x, 1/5)\nR2 = R.subs(x, 4/5)\nsystem = [R1, R2]\nvar = [C1, C2] \nsol = solve(system, var)\nC1_ = sol[C1]\nC2_ = sol[C2]\n\n## POLYNOMIAL ACHIEVED BY THE COLLOCATION METHOD\ny2 = y_.subs([(C1,C1_), (C2,C2_)]).simplify()\ndy2 = dy_.subs([(C1,C1_), (C2,C2_)]).simplify()\nddy2 = ddy_.subs([(C1,C1_), (C2,C2_)]).simplify()\nR_c = -ddy2 - y2 + x**2 \ndisplay(y2)\n\n## VERIFY BOUNDARY CONDITIONS\nprint(\"y(0) = 0: \", y_.subs(x,0).simplify() == 0)\nprint(\"dy(1) = 1: \", dy_.subs(x,1).simplify() == 1)\n\n# EXACT SOLUTION\nx = Symbol('x')\nf = Function('f')(x)\nics = {f.subs(x,0): 0, f.diff(x).subs(x,1): 1}\ndisplay(ics)\node = Eq(-f.diff(x,x) - f + x**2,0)\ndisplay(ode)\nfsol = dsolve(ode, f, ics = ics)\nfsol.simplify()\n\n# POLYNOMIAL - EXACT SOLUTION\nf = x**2 - sin(x)/cos(1) + 2*sin(x)*tan(1) + 2*cos(x) - 2\n\n# PLOT \nfig, ax = plt.subplots(figsize = (12, 7))\nx_range = np.arange(0.0, 1.1, 0.05)\n\nx_ = list()\ny_collocation = list()\ny_exact = list()\n\n\nfor i in x_range:\n x_.append(i)\n value_collocation = y2.subs([(x, i)])\n y_collocation.append(value_collocation)\n \n value_exact = f.subs([(x, i)])\n y_exact.append(value_exact)\n \nplt.plot(x_, y_exact, '-s')\nplt.plot(x_, y_collocation, '-*')\nplt.xlim([0, 1])\nplt.legend([\"$Exact \\, Solution$\",\"$Collocation \\, method$\"])\nplt.grid()\nplt.show()\nfig.savefig('Lista01_Q8a.png',dpi=300) # save figure as png (dpi = number of pixels)\n", "meta": {"hexsha": "537400b2a43932c341f5baad61d1ac7b6c91303a", "size": 1728, "ext": "py", "lang": "Python", "max_stars_repo_path": "Colocation_Method.py", "max_stars_repo_name": "PortelaRenan/FiniteElementCodes", "max_stars_repo_head_hexsha": "63b08f03361ee49342572c80c7ed799908a72591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Colocation_Method.py", "max_issues_repo_name": "PortelaRenan/FiniteElementCodes", "max_issues_repo_head_hexsha": "63b08f03361ee49342572c80c7ed799908a72591", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Colocation_Method.py", "max_forks_repo_name": "PortelaRenan/FiniteElementCodes", "max_forks_repo_head_hexsha": "63b08f03361ee49342572c80c7ed799908a72591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4415584416, "max_line_length": 85, "alphanum_fraction": 0.6116898148, "include": true, "reason": "import numpy,from sympy", "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611574955211, "lm_q2_score": 0.9399133439350608, "lm_q1q2_score": 0.9026562669269608}} {"text": "# MSDS 400 Module 9 Practice 2\n\nfrom numpy import linspace, math\nimport matplotlib.pyplot as plt\n\n'''\nThis particular module takes a few seconds to load. Be patient. Using the\nNumPy math library does speed things up somewhat. When the prompt asks for a\nvalue, enter it and a plot will appear.\n\nThe program will ask for a user supplied value to be entered at the prompt.\nThe integration will use the standard normal density function to find the\nprobability that a standard normal random variable will be <= the value\nspecified by the user A plot will show the area integrated, the user\nsupplied value and the area under the curve.\n'''\n\n# This is the density function for a standard normal distribution.\n\n\ndef f(inp):\n return (math.exp(-inp * inp / 2)) / math.sqrt(2.0 * math.pi)\n\n'''\nThe following values determine the total interval considered and also\nthe increment used for numerical integration. We are dividing 12 standard\ndeviations into 1200 subintervals thus defining delta.\n'''\nxa = -6.0\nxb = 6.0\nnum = 1200\ndelta_calc = float((xb - xa) / num)\n\n\ndef integrate(a, b, delta): # Simpson's rule is used to integrate over [a,b].\n total = 0.0\n i = 0\n n = int(float((b - a) / delta))\n if b == a:\n return\n else:\n while i < n:\n x0 = a + delta * i\n x1 = x0 + delta / 2\n x2 = x0 + delta\n total = total + delta * (f(x0) + 4.0 * f(x1) + f(x2)) / 6\n i = i + 1\n return total\n\n\nx = linspace(xa, xb, num)\ny = []\ncdf = []\n\nfor z in x:\n y = y + [f(z)]\n cdf = cdf + [integrate(xa, z, delta_calc)]\n\nprint('Value of the variable x for integration=?')\nvalue = float(input())\n\nfvalue = integrate(-6, value, delta_calc)\nfvalue = round(fvalue, 4)\nprint('Area with x= {} equals {}'.format(value, fvalue))\n\nplt.xlim(xa - 1, xb + 1)\nplt.ylim(0, 1)\n\nstring = ' with x = ' + str(value) + ' and area = ' + str(fvalue)\nplt.title('Normal Density and CDF' + string)\nplt.xlabel('x-axis')\n\nplt.plot(x, y, 'b', label='Density')\nplt.plot(x, cdf, 'r', label='CDF')\nplt.legend()\n\nplt.fill_between(x, y, where=(x <= value), color='grey', alpha='0.3')\nplt.scatter(value, fvalue, s=30, c='r', marker='o')\nplt.show()\n\n\n# Exercise #1: Refer to Lial Chapter 18 Section 18.3. Using this code,\n# reproduce the results shown in Example 3(c).\n\n# Exercise #2: Refer to Lial Chapter 18 Section 18.3. Using this code,\n# reproduce the results in Example 4 part(a).\n\n", "meta": {"hexsha": "9f47c0bfa57b19aa2cc11afe6e8cf3deaa7b50dd", "size": 2427, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Module 9/practice/Module 9 Practice 2.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Module 9/practice/Module 9 Practice 2.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Module 9/practice/Module 9 Practice 2.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5795454545, "max_line_length": 78, "alphanum_fraction": 0.651421508, "include": true, "reason": "from numpy", "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574669, "lm_q2_score": 0.9416541577509315, "lm_q1q2_score": 0.9026110384930921}} {"text": "#import skfuzzy\r\nimport numpy as np\r\nfrom math import pi\r\nfrom scipy.special import erf\r\nimport matplotlib.pylab as plt\r\n\r\n#________________________V-shaped transfer functions______________________\r\ndef v1(x):\r\n v1=abs(erf((np.sqrt(pi)/2)*x))\r\n return v1\r\n\r\n \r\ndef v2(x):\r\n v2=abs(np.tanh(x))\r\n return v2\r\n \r\n \r\ndef v3(x):\r\n v3= abs(x/np.sqrt(1+np.square(x)))\r\n return v3 \r\n \r\n \r\ndef v4(x):\r\n v4= abs((2/pi)*np.arctan((pi/2)*x))\r\n return v4 \r\n##______________________S-shaped transfer functions_______________________\r\n\r\ndef s1(x):\r\n \r\n s1=1 / (1 + np.exp(-2*x))\r\n \r\n return s1\r\n\r\ndef s2(x):\r\n s2 = 1 / (1 + np.exp(-x)) \r\n return s2\r\n# s2 is called logistic function and can be imported using scipy.special.expit(x) library\r\n\r\ndef s3(x):\r\n s3=1 / (1 + np.exp(-x/3))\r\n return s3\r\n\r\n\r\ndef s4(x):\r\n s4=1 / (1 + np.exp(-x/2))\r\n return s4\r\n\r\n\r\n##________________________the sigmoid functions_________________________\r\n\r\n# A customized function for SIGMOID \r\n\r\ndef sigmf1(x,b,c):\r\n b=10\r\n c=.5\r\n y = 1 / (1. + np.exp(- c * (x - b)))\r\n \r\n return y\r\n\r\n\r\n\r\n## Built-in function for SIGMOID using skfuzzy.membership library\r\n\r\ndef sigmf2(x,b,c):\r\n b=10\r\n c=.5\r\n y=skfuzzy.membership.sigmf(x,b,c)\r\n\r\n return y\r\n\r\n\r\nx = np.arange(-8, 8, 0.1) \r\n# x is used inside this script and will be replaced by a binary individual (1-d binary vector)\r\n#when the transfer function is called or imported in the optimizers scripts\r\n", "meta": {"hexsha": "b398351bd633ba575694e4f81633636746d75c6b", "size": 1489, "ext": "py", "lang": "Python", "max_stars_repo_path": "transfer_functions_benchmark.py", "max_stars_repo_name": "hritam-98/PCA-GWO-cervical-cytology", "max_stars_repo_head_hexsha": "80647c3f51f68007ec5902cd50aec5e7b9a3a132", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-06-10T14:42:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T08:15:37.000Z", "max_issues_repo_path": "transfer_functions_benchmark.py", "max_issues_repo_name": "hritam-98/PCA-GWO-Cervical-cytology", "max_issues_repo_head_hexsha": "80647c3f51f68007ec5902cd50aec5e7b9a3a132", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-01T13:34:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T12:03:38.000Z", "max_forks_repo_path": "transfer_functions_benchmark.py", "max_forks_repo_name": "hritam-98/PCA-GWO-Cervical-cytology", "max_forks_repo_head_hexsha": "80647c3f51f68007ec5902cd50aec5e7b9a3a132", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-10-04T08:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T10:36:19.000Z", "avg_line_length": 19.8533333333, "max_line_length": 95, "alphanum_fraction": 0.6165211551, "include": true, "reason": "import numpy,from scipy", "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290963960278, "lm_q2_score": 0.929440403324091, "lm_q1q2_score": 0.9026066190340841}} {"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 6 22:33:31 2019\r\n\r\n@author: Ham\r\n\r\nHackerRanch Challenge: Eye and Identity\r\n\r\nidentity\r\n\r\nThe identity tool returns an identity array.\r\nAn identity array is a square matrix\r\nwith all the main diagonal elements as 1 and the rest as 0.\r\nThe default type of elements is float.\r\n\r\nimport numpy\r\nprint numpy.identity(3) #3 is for dimension 3 X 3\r\n\r\n#Output\r\n[[ 1. 0. 0.]\r\n [ 0. 1. 0.]\r\n [ 0. 0. 1.]]\r\n\r\neye\r\n\r\nThe eye tool returns a 2-D array with 1's as the diagonal and 0's elsewhere.\r\nThe diagonal can be main, upper or lower depending on the optional parameter k.\r\nA positive k is for the upper diagonal, a negative k is for the lower,\r\nand a k=0 (default) is for the main diagonal.\r\n\r\nimport numpy\r\nprint numpy.eye(8, 7, k = 1) # 8 X 7 Dimensional array with first upper diagonal 1.\r\n\r\n#Output\r\n[[ 0. 1. 0. 0. 0. 0. 0.]\r\n [ 0. 0. 1. 0. 0. 0. 0.]\r\n [ 0. 0. 0. 1. 0. 0. 0.]\r\n [ 0. 0. 0. 0. 1. 0. 0.]\r\n [ 0. 0. 0. 0. 0. 1. 0.]\r\n [ 0. 0. 0. 0. 0. 0. 1.]\r\n [ 0. 0. 0. 0. 0. 0. 0.]\r\n [ 0. 0. 0. 0. 0. 0. 0.]]\r\n\r\nprint numpy.eye(8, 7, k = -2) # 8 X 7 Dimensional array with second lower diagonal 1.\r\n\r\nTask\r\n\r\nYour task is to print an array of size NxM\r\nwith its main diagonal elements as 1's and 0's everywhere else.\r\n\r\nInput Format\r\n\r\nA single line containing the space separated values of N and M.\r\nN denotes the rows.\r\nM denotes the columns.\r\n\r\nOutput Format\r\n\r\nPrint the desired NxM array.\r\n\r\nSample Input\r\n\r\n3 3\r\n\r\nSample Output\r\n\r\n[[ 1. 0. 0.]\r\n [ 0. 1. 0.]\r\n [ 0. 0. 1.]]\r\n\r\n\"\"\"\r\n\r\nimport numpy\r\n\r\nif __name__ == '__main__':\r\n numpy.set_printoptions(legacy='1.13')\r\n # The legacy= stuff above came from the Discussion forum\r\n #n, m = map(int, input().strip().split())\r\n print(numpy.eye(*map(int, input().strip().split())))\r\n", "meta": {"hexsha": "ed3344bb1045e7d1173b26aaea6488f048b70558", "size": 1853, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/one-liner/numpy_eye.py", "max_stars_repo_name": "Hamng/python-sources", "max_stars_repo_head_hexsha": "0cc5a5d9e576440d95f496edcfd921ae37fcd05a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/one-liner/numpy_eye.py", "max_issues_repo_name": "Hamng/python-sources", "max_issues_repo_head_hexsha": "0cc5a5d9e576440d95f496edcfd921ae37fcd05a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-23T18:30:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-23T18:30:51.000Z", "max_forks_repo_path": "python/one-liner/numpy_eye.py", "max_forks_repo_name": "Hamng/python-sources", "max_forks_repo_head_hexsha": "0cc5a5d9e576440d95f496edcfd921ae37fcd05a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1625, "max_line_length": 88, "alphanum_fraction": 0.5990286023, "include": true, "reason": "import numpy", "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.9511422265713299, "lm_q1q2_score": 0.9025552838987847}} {"text": "# 1. A famous researcher observed that chimpanzees hunt and eat meat as part of their regular diet. \n# Sometimes chimpanzees hunt alone, while other times they form hunting parties. The following table \n# summarizes research on chimpanzee hunting parties, giving the size of the hunting party and the percentage \n# of successful hunts. Use Python to graph the data and find the least squares line. Then use the equation \n# to predict the percentage of successful hunts, and the rate that percentage is changing, if there are 20 \n# chimpanzees in a hunting party.\n \nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])\ny = np.array([15, 25, 23, 39, 35, 53, 40, 57, 60, 58, 70, 70, 73, 70, 70, 77])\nA = np.vstack([x, np.ones(len(x))]).T\nprint(A)\n\nm, c = np.linalg.lstsq(A, y)[0]\nprint(m, c)\n\nx2 = np.append([x], [20])\ny2 = np.append([y], [m * 20 + c])\nplt.plot(x, y, 'o', label = 'Data', markersize = 6)\nplt.plot(x2, m * x2 + c, 'b', label = 'Fitted')\nplt.plot(20, m * 20 + c, 'rs')\nplt.legend()\nplt.show()\n\nprint('Expected Percentage with 20 Chimps:', m * 20 + c)\nprint('Rate of change:', m)\n\n# 2. One gram of soybean meal provides at least 2.5 units of vitamins and 5 calories. \n# One gram of meat byproducts provides at least 4.5 units of vitamins and 3 calories. \n# One gram of grain provides at least 5 units of vitamins and 10 calories. If a gram of \n# soybean costs 6 cents, a gram of meat byproducts costs 7 cents, and a gram of grain costs 8 cents, \n# use Python to determine what mixture of the three ingredients will provide at least 48 units of vitamins \n# and 54 calories per serving at a minimum cost? What will be the minimum cost?\n\nfrom scipy.optimize import linprog as lp\nimport numpy as np\n\n# minimize: 6x + 7y + 8z\n# subject to:\n# 2.5x + 4.5y + 5z >= 48\n# 5x + 3y + 10z >= 54\n# x, y, z >= 0\n\nA = np.array([[-2.5, -4.5, -5], [-5, -3, -10]])\nb = np.array([-48, -54])\nbuy = lp(np.array([6, 7, 8]), A, b)\n\nprint('Buy', buy.x[0], 'grams soybean,', \n buy.x[1], 'grams meat byproducts, and',\n buy.x[2], 'grams grain.')\nprint('Minimum per serving cost = $', \n sum(buy.x * np.array([6, 7, 8])) / 100)\n\n# 3. A new test has been developed to detect a particular type of cancer. The test must be evaluated before it is put \n# into use. A medical researcher selects a random sample of 1,000 adults and finds (by other means) that 4% have this \n# type of cancer. Each of the 1,000 adults is given the new test, and it is found that the test indicates cancer in 99% \n# of those who have it and in 1% of those who do not. \n# a) Based on these results, what is the probability of a randomly chosen person having cancer given that the test indicates cancer? \n# b) What is the probability of a person having cancer given that the test does not indicate cancer?\n\nhas_cancer = 0.04\ntrue_pos = 0.99\nfalse_pos = 0.01\n\na = has_cancer * true_pos\nb = (1 - has_cancer) * false_pos\nprob = a / (a + b)\nprint(\"a) Probability that person has cancer given that the test indicates cancer:\",\n round(prob * 100, 3), \"%.\")\n\na = has_cancer * (1 - true_pos) # False neg\nb = (1 - has_cancer) * (1 - false_pos) # True neg\nprob = a / (a + b)\nprint(\"b) Probability that person has cancer given that the test doesn't indicates cancer:\",\n round(prob * 100, 3), \"%.\")\n\n# 4. The following is a graph of a third-degree polynomial with leading coefficient 1. Determine the function depicted \n# in the graph. Using Python, recreate the graph of the original function, 𝑓(𝑥), as well as the graph of its first and \n# second derivatives.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n y = (x + 3) * (x + 1) * (x - 2)\n return (y)\n\ndef g(x):\n #f(x) = x^3 + 2x^2 - 5x - 6\n y = 3 * x ** 2 + 4 * x - 5\n return(y)\n\ndef h(x):\n y = 6 * x + 4\n return(y)\n\nx = np.arange(-4, 4.5, 0.5)\n\nplt.plot(x, f(x), 'b', label = 'y = f(x)')\nplt.plot(x, g(x), 'b-.', label = \"y = f'(x)\")\nplt.plot(x, h(x), 'b--', label = \"y = f''(x)\")\nplt.plot( 1, f( 1), 'ys')\nplt.plot(-2, f(-2), 'ys')\nplt.plot( 2, f( 2), 'rs')\nplt.plot(-1, f(-1), 'rs')\nplt.plot(-3, f(-3), 'rs')\nplt.plot(x, x * 0, 'g')\nplt.legend()\nplt.show()\n\n# 5. For a certain drug, the rate of reaction in appropriate units is given by 𝑅'𝑡=4/(𝑡+1) + 3/sqrt(𝑡+1) where 𝑡 is time (in hours) \n# after the drug is administered. Calculate the total reaction to the drug from 𝑡=1 to 𝑡=12.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\n\ndef f(t):\n y = 4 * np.log(1 + t) + 6 * np.sqrt(1 + t)\n return (y)\n\ndef g(t):\n y = 4 / (t + 1) + 3 / (np.sqrt(1 + t))\n return (y)\n\nt = np.arange(1, 12.5, 0.5)\nplt.plot(t, f(t), 'b', label = 'R(t)')\nplt.plot(t, g(t), 'r', label = \"R'(t)\")\nplt.legend()\nplt.show()\n\ntotal = f(12) - f(1)\nprint(total)\n\n# Confirm\nfunc = lambda t: 4 / (t + 1) + 3 / (np.sqrt(1 + t))\ntotal = integrate.quad(func, 1, 12)\nprint(total[0])\nprint(\"Total reaction from t=1 to t=12 is\", \n round(total[0], 4))\n\n# 6. The nationwide attendance per day for a certain summer blockbuster can be approximated using the equation \n# 𝐴(𝑡)=13𝑡^2𝑒^-t, where A is the attendance per day in thousands of people and t is the number of months since the \n# release of the film. Find and interpret the rate of change of the daily attendance after 4 months and interpret \n# the result.\n\nimport numpy as np\nfrom scipy.misc import derivative\nimport matplotlib.pyplot as plt\n\ndef A(t):\n y = 13 * t**2 * np.exp(-t)\n return (y)\n\nh = 1e-5\na = (A(4+h) - A(4)) / h\nprint(a)\nprint(A(np.arange(0, 6, 1)))\n\nt = np.arange(0, 10, 1)\nplt.plot(t, A(t), 'b', label = 'A(t)')\nplt.plot(t, derivative(A, t, dx = 1e-5), 'r--', label = \"A'(t)\")\nplt.legend()\nplt.show()\n\n# Confirm\nder = derivative(A, 4, dx = 1e-5)\nprint(der)\nprint(\"Rate of change at t=4\", der)\n\n# 7. The population of mathematicians in the eastern part of Evanston is given by the formula 𝑃(𝑡)=(𝑡^2+100) * ln(𝑡+2), \n# where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006.\n\nimport numpy as np\nfrom scipy.misc import derivative\nimport matplotlib.pyplot as plt\n\ndef P(t):\n y = (t**2 + 100) * np.log(t + 2)\n return (y)\n\nh = 1e-5\na = (P(6 + h) - P(6)) / h\nprint(a)\n\nt = np.arange(0, 10, 1)\nplt.plot(t, P(t), 'b', label = 'P(t)')\nplt.plot(t, derivative(P, t, dx = 1e-5), 'r--', label = \"P'(t)\")\nplt.legend()\nplt.show()\n\n# Confirm\nder = derivative(P, 6, dx = 1e-5)\nprint(der)\nprint(\"Rate of change at t=2006\", der)\n\n# 8. The rate of change in a person's body temperature, with respect to the dosage of x milligrams of a certain diuretic, \n# is given by 𝐷′(x) = 2 / (x+6). One milligram raises the temperature 2.2°C. Find the function giving the total \n# temperature change. If someone takes 5 milligrams of this diuretic what will their body temperature be, assuming they \n# start off at a normal temperature of 37oC?\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n y = 2 * np.log(x + 6)\n return (y)\n\ndef g(x):\n y = 2 / (x + 6)\n return (y)\n\ntemp = 37\nC = 2.2 - f(1)\n\nt = np.arange(0, 5.5, 0.5)\nplt.plot(t, f(t) + C, 'b', label = 'D(x)')\nplt.plot(t, g(t), 'r--', label = \"D'(x)\")\nplt.legend()\nplt.show()\n\nnew_temp = f(5) + C + temp\nprint(new_temp)\nprint(\"Temp after taking 5 milligrams=\", new_temp)\n\n# 9. The following function represents the life of a lightbulb in years based on average consumer usage. \n# Show 𝑓(𝑥) is a probability density function on [0,∞). \n# 𝑓(𝑥) = x^3/12, if 0 <= x <= 2\n# 𝑓(𝑥) = 16/x^4, if x > 2\n# Determine the probability a lightbulb will last between 1 and 5 years.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx1 = np.arange(0, 2.1, 0.1)\nx2 = np.arange(2.1, 20, 0.1)\n\ndef f(x):\n y = x**3 / 12\n return (y)\n\ndef f2(x):\n y = 16 / x**4\n return(y)\n\nplt.plot(x1, f(x1), 'b')\nplt.plot(x2, f2(x2), 'r')\nplt.legend()\nplt.show()\n\ntot = 0\nfor x in range(5000000):\n val = x / 100\n if (val <= 2): tot += f(val)\n if (val > 2): tot += f2(val) \nprint(\"f(x) for [0,inf) is \", round(tot / 100, 2), \n \"and is a probability density\")\n\ntot = 0\nfor x in range(100, 500):\n val = x / 100\n if (val <= 2): tot += f(val)\n if (val > 2): tot += f2(val) \nprint(tot)\nprint(\"Probability lightbulb lasts 1-5 years=\",\n tot, \"%\")\n", "meta": {"hexsha": "30f32b94af5701de91cd657db8838a0b3466825a", "size": 8296, "ext": "py", "lang": "Python", "max_stars_repo_path": "predict400/ex2.py", "max_stars_repo_name": "TJConnellyContingentMacro/northwestern", "max_stars_repo_head_hexsha": "116301f68e9ce02bc13d5496b3e4cec98154f7d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predict400/ex2.py", "max_issues_repo_name": "TJConnellyContingentMacro/northwestern", "max_issues_repo_head_hexsha": "116301f68e9ce02bc13d5496b3e4cec98154f7d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predict400/ex2.py", "max_forks_repo_name": "TJConnellyContingentMacro/northwestern", "max_forks_repo_head_hexsha": "116301f68e9ce02bc13d5496b3e4cec98154f7d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-12T01:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T23:08:10.000Z", "avg_line_length": 30.8401486989, "max_line_length": 133, "alphanum_fraction": 0.6360896818, "include": true, "reason": "import numpy,from scipy", "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9732407191430025, "lm_q2_score": 0.9273632876167045, "lm_q1q2_score": 0.9025477129469005}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(-10, 10, 0.001)\ny = 1 / (1 + np.exp(-x))\nplt.plot(x, y)\nplt.suptitle(r'$y=\\frac{1}{1+e^{-x}}$', fontsize=20)\nplt.grid(color='gray')\nplt.grid(linewidth='1')\nplt.grid(linestyle='--')\nplt.show()\n\nx = np.linspace(-10, 10, 100)\ny = 1 / (1 + np.exp(-x))\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"sigmoid function and its derivative image\")\nplt.plot(x, y, color='r', label=\"sigmoid\")\ny = np.exp(-x) / pow((1 + np.exp(-x)), 2)\nplt.plot(x, y, color='b', label=\"sigmoid derivative\")\nplt.legend() # 将plot标签里面的图注印上去\nplt.show()\n\nr = np.linspace(-20, 20, 500)\nplt.xlabel(\"r\")\nplt.ylabel(\"y\")\nplt.title(\"Gaussian RBF\")\nfor delta in [1, 5, 0.5]:\n y = np.exp(-(r ** 2 / (2 * delta ** 2)))\n plt.plot(r, y, label=\"δ = \" + str(delta))\n\nplt.legend() # 将plot标签里面的图注印上去\nplt.show()\n\nr = np.linspace(-20, 20, 500)\nplt.xlabel(\"r\")\nplt.ylabel(\"y\")\nplt.title(\"Inverse multiquadrics RBF\")\nfor delta in [1, 5, 0.5]:\n y = 1 / (np.sqrt(r ** 2 + delta ** 2))\n plt.plot(r, y, label=\"δ = \" + str(delta))\n\nplt.legend()\nplt.show()\n\nr = np.linspace(-10, 10, 500)\nplt.xlabel(\"r\")\nplt.ylabel(\"y\")\nplt.title(\"Reflected Sigmoidal RBF\")\nfor delta in [1, 5, 0.5]:\n y = 1 / (1 + np.exp(r ** 2 / delta ** 2))\n plt.plot(r, y, label=\"δ = \" + str(delta))\n\nplt.legend()\nplt.show()\n\n\n# mpmath 绘制图像\n# import mpmath as mp\n# mp.plot(lambda x: x*x, [-10, 10])\n\n# mpmath 绘制三维图像\n# import mpmath as mp\n# import math\n# mp.splot(lambda x, y: x*math.exp(-x*x-y*y))\n\n# sympy 绘制图像\n# from sympy.plotting import plot\n# from sympy import symbols\n#\n# x = symbols('x')\n# p2 = plot(x*x, (x, -10, 10))\nfrom sympy.plotting import plot\nfrom sympy import symbols\nfrom sympy.functions import exp\n\nr = symbols('r')\np = []\nfor delta in [1, 5, 0.5]:\n y = 1 / (1 + exp(r ** 2 / delta ** 2))\n p.append((y, (r, -10, 10)))\np2 = plot(*p)\n\n# import mpmath as mp\n# import math\n# mp.plot(lambda r: 1 / (1 + math.exp(r ** 2 / delta ** 2)), [-10, 10])\n\n", "meta": {"hexsha": "cd813b724305d595c0683b2a526fbdf0a902fff2", "size": 1959, "ext": "py", "lang": "Python", "max_stars_repo_path": "matplotlib/rbf.py", "max_stars_repo_name": "kingreatwill/penter", "max_stars_repo_head_hexsha": "2d027fd2ae639ac45149659a410042fe76b9dab0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-01-04T07:37:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T05:19:58.000Z", "max_issues_repo_path": "matplotlib/rbf.py", "max_issues_repo_name": "kingreatwill/penter", "max_issues_repo_head_hexsha": "2d027fd2ae639ac45149659a410042fe76b9dab0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-06-05T22:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T07:18:54.000Z", "max_forks_repo_path": "matplotlib/rbf.py", "max_forks_repo_name": "kingreatwill/penter", "max_forks_repo_head_hexsha": "2d027fd2ae639ac45149659a410042fe76b9dab0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-10-19T04:53:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T05:20:01.000Z", "avg_line_length": 22.2613636364, "max_line_length": 71, "alphanum_fraction": 0.5952016335, "include": true, "reason": "import numpy,from sympy,import mpmath", "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570261, "lm_q2_score": 0.9324533088603709, "lm_q1q2_score": 0.9025208978019205}} {"text": "import numpy as np\n\n\"\"\"\nA2-Part-2: Generate a complex sinusoid \n\nWrite a function to generate the complex sinusoid that is used in DFT computation of length N (samples), \ncorresponding to the frequency index k. Note that the complex sinusoid used in DFT computation has a \nnegative sign in the exponential function.\n\nThe amplitude of such a complex sinusoid is 1, the length is N, and the frequency in radians is 2*pi*k/N.\n\nThe input arguments to the function are two positive integers, k and N, such that k < N-1. \nThe function should return cSine, a numpy array of the complex sinusoid.\n\nEXAMPLE: If you run your function using N=5 and k=1, the function should return the following numpy array cSine:\narray([ 1.0 + 0.j, 0.30901699 - 0.95105652j, -0.80901699 - 0.58778525j, -0.80901699 + 0.58778525j, \n0.30901699 + 0.95105652j])\n\"\"\"\ndef genComplexSine(k, N):\n \"\"\"\n Inputs:\n k (integer) = frequency index of the complex sinusoid of the DFT\n N (integer) = length of complex sinusoid in samples\n Output:\n The function should return a numpy array\n cSine (numpy array) = The generated complex sinusoid (length N)\n \"\"\"\n ## Your code here\n time_domain = np.arange(0, N)\n x = np.exp(-1j * 2 * np.pi * k * time_domain / N)\n return(x)\n\n", "meta": {"hexsha": "bd003075ceaaa23565ed20e9d626b62ff8d67486", "size": 1280, "ext": "py", "lang": "Python", "max_stars_repo_path": "A2/A2Part2.py", "max_stars_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_stars_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "A2/A2Part2.py", "max_issues_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_issues_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A2/A2Part2.py", "max_forks_repo_name": "mortarsynth/Audio-Signal-Processing-for-Music-Applications", "max_forks_repo_head_hexsha": "4674d9e15885401d69d4a468e3ad756ea2600523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7878787879, "max_line_length": 112, "alphanum_fraction": 0.703125, "include": true, "reason": "import numpy", "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924793940118, "lm_q2_score": 0.9284088020410762, "lm_q1q2_score": 0.9024063733871299}} {"text": "#This problem was asked by Amazon.[EASY}\n\n#Given n numbers, find the greatest common denominator between them.\n\n#For example, given the numbers [42, 56, 14], return 14.\n#Solution using numpy\nimport numpy as np\n\nA = [14,56,42]\n\nprint(np.gcd.reduce(A))\n\n#Solution: Scaling for any number of input values\nn = int(input('HOW MANY NUMBERS YOU WANT TO CALCULATE GCD?: '))\na = list(map(int,input('ENTER THE NUMBER TO COMPUTE GCD: ').strip().split()))[:n]\n\ndef compute_gcd(num1,num2):\n x = 1\n while x:\n if max(num1,num2) % min(num1,num2) == 0:\n return min(num1,num2)\n x = 0\n else :\n r = max(num1,num2)%min(num1,num2)\n return compute_gcd(max(num1,num2),r)\n\nwhile True:\n a[0] = compute_gcd(a[0],a[1])\n a.pop(1)\n if len(set(a))>2:\n a.pop(2)\n if len(set(a)) == 1:\n break\na = set(a)\nprint(f\"GCD OF {n} NUMBERS IS {a}\")\n\n#Solution by Euclidean algo with loops for more than 2 numbers\ndef compute_gcd(x, y):\n \n while(y):\n x, y = y, x % y\n \n return x\n \n# Driver Code \nl = [ 42, 56, 14]\n \nnum1 = l[0]\nnum2 = l[1]\ngcd = compute_gcd(num1, num2)\n \nfor i in range(2, len(l)):\n gcd = compute_gcd(gcd, l[i])\n \nprint(f\"the gcd among the numbers {l} is {gcd}\")\n\n#Solution using functools:\n\nimport functools as f\nA = [56, 42, 14]\ng = lambda a,b:a if b==0 else g(b,a%b) #Gcd for two numbers\nprint(f.reduce(lambda x,y:g(x,y),A)) #Calling gcd function throughout the list.\n\n\n# Solution using maths in fixed set of numbers:\nimport math\nA=[56,42,14]\nb=A[0] \nfor j in range(1,len(A)):\n s=math.gcd(b,A[j])\n b=s\nprint(f'GCD of array elements is {b}.')\n\n# Solution using maths.gcd for n numbers\nimport math\ndef compute_gcd(lst):\n \n if len(lst) == 0: # trivial case\n return -1\n while len(lst) > 1:\n a = lst.pop()\n b = lst.pop()\n c = math.gcd(a,b) if a >= b else math.gcd(b, a)\n lst.append(c)\n return lst.pop()\ndef test_gcd():\n assert compute_gcd([42, 56, 14]) == 14\n assert compute_gcd([3, 6]) == 3\n assert compute_gcd([1]) == 1\n assert compute_gcd([]) == -1\n\nif __name__ == \"__main__\":\n test_gcd()\n", "meta": {"hexsha": "b712ae0276c84742e181ea4c4e82d144df318ea3", "size": 2196, "ext": "py", "lang": "Python", "max_stars_repo_path": "amz_find_gcd.py", "max_stars_repo_name": "PN1019/DailyCodingProblems", "max_stars_repo_head_hexsha": "34a853c1c56d4e653f7b890935eabf0b88d5abe8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "amz_find_gcd.py", "max_issues_repo_name": "PN1019/DailyCodingProblems", "max_issues_repo_head_hexsha": "34a853c1c56d4e653f7b890935eabf0b88d5abe8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amz_find_gcd.py", "max_forks_repo_name": "PN1019/DailyCodingProblems", "max_forks_repo_head_hexsha": "34a853c1c56d4e653f7b890935eabf0b88d5abe8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3617021277, "max_line_length": 83, "alphanum_fraction": 0.5824225865, "include": true, "reason": "import numpy", "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.9425067232182671, "lm_q1q2_score": 0.9022407625025375}} {"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.spatial import ConvexHull, convex_hull_plot_2d\n\n## Ejemplo 2D\nrng = np.random.default_rng()\npoints = rng.random((100, 2)) # 30 random points in 2-D\nhull = ConvexHull(points)\nplt.plot(points[:,0], points[:,1], 'o')\nfor simplex in hull.simplices:\n plt.plot(points[simplex, 0], points[simplex, 1], 'k--')\n \n## Ejemplo 3D\nrng = np.random.default_rng()\npoints3d = rng.random((300, 3)) # 30 random points in 2-D\nhull3d = ConvexHull(points3d)\nvertices3d = points3d[hull3d.vertices,:]\n\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\nax.scatter(points3d[:,0], points3d[:,1], points3d[:,2], c='black')\nax.scatter(vertices3d[:,0], vertices3d[:,1], vertices3d[:,2], c='red') \n \nfor simplex in hull3d.simplices:\n ax.plot(points3d[simplex, 0], points3d[simplex, 1], points3d[simplex, 2], 'g--')\n \nplt.show()\n\nsimplices = hull3d.simplices\n\nout = []\n\nfor i in simplices:\n p0 = points3d[i[0],:]\n p1 = points3d[i[1],:]\n p2 = points3d[i[2],:]\n \n temp = [p0, p1, p2]\n out.append(temp)\n \npoints_simplices = np.array(out)\n", "meta": {"hexsha": "cfa925afd62599a3051857773817881252ca70c1", "size": 1149, "ext": "py", "lang": "Python", "max_stars_repo_path": "4.convex_hull_3d/test.py", "max_stars_repo_name": "jmflorezr/computational_geometry", "max_stars_repo_head_hexsha": "af1819da263bbae88f4bf08658ae250cb8c6681b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-17T13:52:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:52:51.000Z", "max_issues_repo_path": "4.convex_hull_3d/test.py", "max_issues_repo_name": "jmflorezr/computational_geometry", "max_issues_repo_head_hexsha": "af1819da263bbae88f4bf08658ae250cb8c6681b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.convex_hull_3d/test.py", "max_forks_repo_name": "jmflorezr/computational_geometry", "max_forks_repo_head_hexsha": "af1819da263bbae88f4bf08658ae250cb8c6681b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-15T16:30:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T16:30:05.000Z", "avg_line_length": 26.7209302326, "max_line_length": 84, "alphanum_fraction": 0.6527415144, "include": true, "reason": "import numpy,from scipy", "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9808759643671933, "lm_q2_score": 0.9196425394367774, "lm_q1q2_score": 0.9020552627431436}} {"text": "import numpy as np #import scientific computing library\nfrom numba import cuda\nimport matplotlib.pyplot as plt # import plotting library\n# define values for global variables\nTPB = 8 #number of threads per block\n\n\n#function definitions for problem 2\ndef gen_array_1(n):\n \"\"\"Generate an array of n values equally spaced over the\n interval [0,2*Pi] using for loop.\n \"\"\"\n if n < 0:\n return None\n if n == 0:\n return np.array([])\n if n == 1:\n return np.array([0])\n interval = 2 * np.pi / (n - 1)\n array = []\n val = 0\n for i in range(n):\n array.append(val)\n val += interval\n return np.array(array)\n\ndef gen_array_2(n):\n \"\"\"Generate an array of n values equally spaced over the\n interval [0,2*Pi] using numpy's linspace.\n \"\"\"\n return np.linspace(0, 2*np.pi, n)\n\ndef plot_res(n):\n \"\"\"Plot the values as a function of index number.\n \"\"\"\n x = np.array([i for i in range(n)])\n y = gen_array_2(n)\n plt.plot(x, y, 'o')\n plt.show()\n\n#function definitions for problem 3\n# 3a\ndef scalar_mult(u, c):\n \"\"\"Compute scaler multiplication of an array and a number.\n Args: an np.array u, a number c\n Returns: an array \n \"\"\"\n n = u.shape[0]\n out = np.zeros(n)\n for i in range(n):\n out[i] = u[i] * c\n return out\n\n# 3b\ndef component_add(a, b):\n \"\"\"Compute conponent wise addition of two arrays.\n Args: two arrays with same length\n Returns: an numpy array with the same length with input arrays\n \"\"\"\n n = a.shape[0]\n out = np.zeros(n)\n for i in range(n):\n out[i] = a[i] + b[i]\n return out\n\n# 3c\ndef linear_function(c, x, d):\n \"\"\"Evaluate the linear function y = c * x + d\n Args: c,x,d: arrays with the same length\n Returns: the result of the evaluation, an numpy array.\n \"\"\"\n return component_add(scalar_mult(x, c), d)\n\n# 3d\ndef component_mult(a, b):\n \"\"\"Compute the component wise multiplication of two arrays\n Args: two arrays with same length\n Returns: an numpy array\n \"\"\"\n n = a.shape[0]\n out = np.zeros(n)\n for i in range(n):\n out[i] = a[i] * b[i]\n return out\n\n# 3e\ndef inner(a, b):\n \"\"\"Compute the inner product of two arrays\n Args: two arrays with same length\n Returns: a float number\n \"\"\"\n n = a.shape[0]\n out = 0\n for i in range(n):\n out += a[i] * b[i]\n return out\n\n# 3f\ndef norm(a):\n \"\"\"Compute the L2 norm of input array\n Args: an array a\n Return: a float number\n \"\"\"\n n = a.shape[0]\n out = 0\n for i in range(n):\n out += a[i] * a[i]\n return np.sqrt(out)\n\n\n#function definitions for problem 4\n# 4a\n@cuda.jit\ndef scalar_mult_kernel(d_out, d_u, d_c):\n \"\"\"Kernel fucntion to do scalar multiplication\"\"\"\n i = cuda.grid(1)\n n = d_u.shape[0]\n if i >= n:\n return \n d_out[i] = d_u[i] * d_c\n\ndef nu_scalar_mult(u, c):\n \"\"\"Wrapper to do scalar multiplication\n Args: a np array and a scalar number\n Returns: result of the scalar multiplication\n \"\"\"\n n = u.shape[0]\n d_u = cuda.to_device(u)\n # d_c = cuda.to_device(c)\n d_c = c\n d_out = cuda.device_array(n)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n scalar_mult_kernel[blocks, threads](d_out, d_u, d_c)\n return d_out.copy_to_host()\n\n\n# 4b\n@cuda.jit\ndef component_add_kernel(d_out, d_u, d_v):\n \"\"\"Kernel function to do component wise add\"\"\"\n i = cuda.grid(1)\n n = d_u.shape[0]\n if i >= n:\n return \n d_out[i] = d_u[i] + d_v[i]\n\ndef nu_component_add(u, v):\n \"\"\"Wrapper function to do component wise add.\n Args: two numpy arrays\n Returns: a numpy array, the sum of inputs\n \"\"\"\n n = u.shape[0]\n d_u = cuda.to_device(u)\n d_v = cuda.to_device(v)\n d_out = cuda.device_array(n)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n component_add_kernel[blocks, threads](d_out, d_u, d_v)\n return d_out.copy_to_host()\n\n\n# 4c\n\n@cuda.jit\ndef linear_function_kernel(d_out, d_c, d_x, d_d):\n \"\"\"Kernel function the calculate linear function\"\"\"\n i = cuda.grid(1)\n n = d_x.shape[0]\n if i >= n:\n return \n d_out[i] = d_c * d_x[i] + d_d[i]\n\ndef nu_linear_function(c, x, d):\n \"\"\"Wrapper function to calculate linear function.\n Args: a scaler, a numpy array, another numpy array as bias\n Return: a numpy array.\n \"\"\"\n n = x.shape[0]\n d_c = c\n d_x = cuda.to_device(x)\n d_d = cuda.to_device(d)\n d_out = cuda.device_array(n)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n linear_function_kernel[blocks, threads](d_out, d_c, d_x, d_d)\n return d_out.copy_to_host()\n\n\n# 4d \n@cuda.jit\ndef component_mult_kernel(d_out, d_u, d_v):\n \"\"\"Kernel function to do component wise multiplication.\"\"\"\n i = cuda.grid(1)\n n = d_u.shape[0]\n if i >= n:\n return \n d_out[i] = d_u[i] * d_v[i]\n\ndef nu_component_mult(u ,v):\n \"\"\"Wrapper function to do component wise multiplication.\n Args: two numpy arrays\n Return: the result, a numpy array\n \"\"\"\n n = u.shape[0]\n d_u = cuda.to_device(u)\n d_v = cuda.to_device(v)\n d_out = cuda.device_array(n)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n component_mult_kernel[blocks, threads](d_out, d_u, d_v)\n return d_out.copy_to_host()\n\n# 4e\n@cuda.jit\ndef inner_kernel(d_accum, d_u, d_v):\n \"\"\"Kernel function to do inner product.\"\"\"\n n = d_u.shape[0]\n i = cuda.grid(1)\n if i >= n:\n return \n # accumulate the component wise product\n cuda.atomic.add(d_accum, 0, d_u[i] * d_v[i])\n\ndef nu_inner(u, v):\n \"\"\"Wrapper function to do inner product.\n Args: two numpy arrays\n Returns: a float number.\n \"\"\"\n n = u.shape[0]\n accum = np.zeros(1)\n d_accum = cuda.to_device(accum)\n d_u = cuda.to_device(u)\n d_v = cuda.to_device(v)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n inner_kernel[blocks, threads](d_accum, d_u, d_v)\n accum = d_accum.copy_to_host()\n return accum[0]\n\n\n\n# 4f\n@cuda.jit\ndef norm_kernel(d_accum, d_u):\n \"\"\"Kernel function to calculate norm.\"\"\"\n n = d_u.shape[0]\n i = cuda.grid(1)\n if i >= n:\n return \n # accumulate the component wise product\n cuda.atomic.add(d_accum, 0, d_u[i] * d_u[i])\n\ndef nu_norm(u):\n \"\"\"Wrapper function to calculate norm.\n Args: a numpy array\n Return: a float number\"\"\"\n n = u.shape[0]\n accum = np.zeros(1)\n d_accum = cuda.to_device(accum)\n d_u = cuda.to_device(u)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n norm_kernel[blocks, threads](d_accum, d_u)\n accum = d_accum.copy_to_host()\n return np.sqrt(accum[0])\n\n\n# function definitions for problem 5\n# 5.a.v reverse dot\n# alternative version of inner kernel: calculate sum serially\n@cuda.jit\ndef inner_kernel_serial(d_uv, d_u, d_v):\n \"\"\"Kernel function to do inner product.\n Returns a numpy array: the component wise multiplication of\n two arrays\n \"\"\"\n n = d_u.shape[0]\n i = cuda.grid(1)\n if i >= n:\n return\n d_uv[i] = d_u[i] * d_v[i]\n\n# sum the contributions in serial order\ndef inner_diff(u, v):\n \"\"\"Calculate the difference between two ways of accumlation \n when doing inner product.\n Args: two numpy arrays.\n Returns: a float number, the inner product.\n \"\"\"\n n = u.shape[0]\n d_u = cuda.to_device(u)\n d_v = cuda.to_device(v)\n uv = np.zeros(n)\n d_uv = cuda.to_device(uv)\n blocks = (n + TPB - 1) // TPB\n threads = TPB\n inner_kernel_serial[blocks, threads](d_uv, d_u, d_v)\n uv = d_uv.copy_to_host()\n sum_s = 0\n sum_r = 0\n for i in range(n):\n # accumulate components from head to tail\n sum_s += uv[i]\n # accumulate components from tail to head\n sum_r += uv[n-i-1]\n print(\"serial dot: \", sum_s)\n print(\"reverse dot: \", sum_r)\n return np.abs(sum_s - sum_r)\n\n\ndef main():\n N_2 = 11\n # Problem 2\n print(\"Problem 2\")\n print(\"2.1\")\n print(\"N = \", N_2, \": \", gen_array_1(N_2))\n print()\n print(\"2.2\")\n print(\"N = \", N_2, \": \", gen_array_2(N_2))\n print()\n print(\"2.3\")\n print(\"See Figure 1.\")\n print()\n\n # Problem 3\n u = np.ones(5)\n v = np.ones(5)\n c = 2\n d = 3\n print(\"Problem 3\")\n print(\"u = \", u)\n print(\"v = \", v)\n print(\"c = \", c)\n print(\"d = \", d)\n print(\"scalar mult: \", scalar_mult(u, c))\n print(\"component add: \", component_add(u, v))\n print(\"component mult: \", component_mult(u,v))\n print(\"linear function: \", linear_function(c, u, v))\n print(\"inner: \", inner(u, v))\n print(\"norm: \", norm(u))\n print()\n\n # Problem 4\n print(\"Problem 4\")\n print(\"u = \", u)\n print(\"v = \", v)\n print(\"c = \", c)\n print(\"d = \", d)\n print(\"scalar mult: \", nu_scalar_mult(u, c))\n print(\"component add: \", nu_component_add(u, v))\n print(\"component mult: \", nu_component_mult(u,v))\n print(\"linear function: \", nu_linear_function(c, u, v))\n print(\"inner: \", nu_inner(u, v))\n print(\"norm: \", nu_norm(u))\n print()\n\n # Problem 5\n N_5 = 5\n print(\"Problem 5\")\n print(\"N = \", N_5)\n v = np.ones(N_5)\n u = np.ones(N_5)\n for i in range(1, N_5):\n u[i] = 1 / (N_5 - 1)\n print(\"5.1\")\n print(\"v = \", v)\n print()\n print(\"5.2\")\n print(\"u = \", u)\n print()\n print(\"5.3\")\n z = nu_scalar_mult(u, -1)\n # print(\"z = -u = \", z)\n print(\"norm(u + z) = \", nu_norm(nu_component_add(u, z)))\n print()\n print(\"5.4\")\n print(\"u dot v = \", nu_inner(u, v))\n print()\n print(\"5.5\")\n # print(\"u reverse dot v = \")\n print(\"Dot result difference: \", inner_diff(u, v))\n print()\n print(\"I repeat 5.5 for larger Ns, here are the result:\")\n print(\"N = 1e4\\nserial dot: 2.0\\nreverse dot: 2.0\\nDot result difference: 9.01723140601e-13\")\n print()\n print(\"N = 1e5\\nserial dot: 2.0\\nreverse dot: 2.0\\nDot result difference: 2.2226664953e-12\")\n print()\n print(\"N = 1e6\\nserial dot: 2.00000000001\\nreverse dot: 2.00000000001\\nDot result difference: 4.08117983852e-13\")\n print()\n print(\"N = 1e7\\nserial dot: 2.0000000005\\nreverse dot: 2.00000000023\\nDot result difference: 2.74033240544e-10\")\n print()\n print(\"N = 1e8\\nserial dot: 2.00000000613\\nreverse dot: 1.99999999776\\nDot result difference: 8.36787017455e-09\")\n print()\n print(\"When N increase to 1e6, the order of summation starts to influnce results.\\nThis is because of the float number round off error. The data type is 'np.float64',\\nso the difference is smaller than the 'np.float32' case.\")\n \n # plot for problem 2.3\n plot_res(N_2)\n plt.close()\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1d672bf515269908272933a349992e0c828dc5e2", "size": 10588, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw1/hw1.py", "max_stars_repo_name": "nqiao/Voxel-Modeling", "max_stars_repo_head_hexsha": "ee4cb96037cfde6adc9ad7b719d1ccf1f5ced5ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw1/hw1.py", "max_issues_repo_name": "nqiao/Voxel-Modeling", "max_issues_repo_head_hexsha": "ee4cb96037cfde6adc9ad7b719d1ccf1f5ced5ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1/hw1.py", "max_forks_repo_name": "nqiao/Voxel-Modeling", "max_forks_repo_head_hexsha": "ee4cb96037cfde6adc9ad7b719d1ccf1f5ced5ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.513253012, "max_line_length": 230, "alphanum_fraction": 0.5986966377, "include": true, "reason": "import numpy,from numba", "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377296574668, "lm_q2_score": 0.9407897459384732, "lm_q1q2_score": 0.901782467156889}} {"text": "import numpy as np\n\n\na = np.array([\n (1, 3, 5, 7),\n (3, 5, 7, 1),\n (5, 7, 1, 3),\n (7, 1, 1, 5)\n], dtype=np.float64)\n\nb = np.array([12, 0, 4, 16], dtype=np.float64)\n\n\ndef solve_gauss_m(a, b):\n a = a.copy()\n b = b.copy()\n\n for i in range(0, a.shape[0]):\n main_row_index = i + np.argmax(a[range(i, a.shape[1]), i])\n main_row_el = a[main_row_index, i]\n\n # Swap main row with ith row\n if main_row_index != i:\n a[[main_row_index, i], :] = a[[i, main_row_index], :]\n b[[main_row_index, i]] = b[[i, main_row_index]]\n # print(a)\n # print(b)\n\n a[i, :] /= main_row_el\n b[i] /= main_row_el\n\n for row_index in range(i + 1, a.shape[1]):\n multiplier = a[row_index, i]\n a[row_index, :] -= a[i, :] * multiplier\n b[row_index] -= b[i] * multiplier\n\n # print(a)\n # print(b)\n\n x = np.empty_like(b)\n\n for i in range(0, a.shape[0]):\n row_index = x.size - 1 - i\n x[row_index] = b[row_index]\n for j in range(0, i):\n x[row_index] -= a[row_index, a.shape[1]-1 - j] * x[x.size-1 - j]\n\n return x\n\n\nMAX_STEPS = 100\n\n\ndef solve_seidel(a, b, max_steps=MAX_STEPS, epsilon=1e-04):\n x = np.zeros_like(b)\n\n for step in range(max_steps):\n x_new = np.zeros_like(x)\n\n for i in range(x.size):\n for j in range(0, i):\n x_new[i] -= a[i, j] / a[i, i] * x_new[j]\n for j in range(i + 1, x.size):\n x_new[i] -= a[i, j] / a[i, i] * x[j]\n x_new[i] += b[i] / a[i, i]\n\n print(\"Step\", step, \":\", x_new)\n\n if np.allclose(x, x_new, atol=epsilon, rtol=0):\n return x_new\n\n x = x_new\n\n return x_new\n\n\nprint(\"Gauss (with selection of main element):\", solve_gauss_m(a, b))\nprint(\"numpy.linalg.solve:\", np.linalg.solve(a, b))\n\na = np.array([\n [3, -1, 1],\n [-1, 2, 0.5],\n [1, 0.5, 3]\n], dtype=np.float64)\nb = np.array([1, 1.75, 2.5], dtype=np.float64)\n\nprint(\"Seidel:\", solve_seidel(a, b, epsilon=0.0001))\nprint(\"numpy.linalg.solve:\", np.linalg.solve(a, b))\n", "meta": {"hexsha": "260c878ed68bb23823d5096c9467185ce233fe09", "size": 2117, "ext": "py", "lang": "Python", "max_stars_repo_path": "semester5/num-methods/lab2/lab2.py", "max_stars_repo_name": "gardenappl/uni", "max_stars_repo_head_hexsha": "5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "semester5/num-methods/lab2/lab2.py", "max_issues_repo_name": "gardenappl/uni", "max_issues_repo_head_hexsha": "5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "semester5/num-methods/lab2/lab2.py", "max_forks_repo_name": "gardenappl/uni", "max_forks_repo_head_hexsha": "5bc7110946caf16aae2a0c1ddae4e88bfbb25aa8", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7865168539, "max_line_length": 76, "alphanum_fraction": 0.5054322154, "include": true, "reason": "import numpy", "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399026119352, "lm_q2_score": 0.9294404077216355, "lm_q1q2_score": 0.9017801706714369}} {"text": "\"\"\"\n\nTanh Function: f(x) = 2g(2x)-1\n = (e^x - e^-x)/(e^x + e^-x)\n\nCreated by: MJ\n\n\"\"\"\n\n\"\"\"\nThe tanh function, a.k.a. hyperbolic tangent function, is a rescaling of the logistic sigmoid, such that its outputs range from -1 to 1. (There’s horizontal stretching as well.)\n\nYes it matters for technical reasons. Basically for optimization. It is worth reading Efficient Backprop by LeCun et al.\n\nThere are two reasons for that choice (assuming you have normalized your data, and this is very important):\n\nHaving stronger gradients: since data is centered around 0, the derivatives are higher. To see this, calculate the derivative of the tanh function and notice that its range (output values) is [0,1].\nThe range of the tanh function is [-1,1] and that of the sigmoid function is [0,1]\n\nAvoiding bias in the gradients. This is explained very well in the paper, and it is worth reading it to understand these issues.\n\"\"\"\nimport numpy as np\nimport math\n\ndef tanh(x,library =\"math\"):\n\tif library == \"math\":\n\t\treturn math.tanh(x)\n\telse:\n\t\treturn np.tanh(x)\n\ndef tanh_derivative(x,library=\"math\"):\n\tif library == \"math\":\n\t\treturn 1- math.tanh(x)**2\n\telse:\n\t\treturn 1-np.tanh(x)**2\n\nif __name__ == \"__main__\":\n\tprint(\"tanh value is: \",tanh(0.75))\n\tprint(\"tanh derivative is: \",tanh_derivative(0.75))", "meta": {"hexsha": "b528b6ed6c3395b7d9550e78955eac458161341c", "size": 1309, "ext": "py", "lang": "Python", "max_stars_repo_path": "activation-functions/python-implementations/tanh.py", "max_stars_repo_name": "manojkumar-github/Implementations-Of-MachineLearning-and-Deep-Learning", "max_stars_repo_head_hexsha": "9e80a56c84073bbf3b5c9d6e8891176e02f0d973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "activation-functions/python-implementations/tanh.py", "max_issues_repo_name": "manojkumar-github/Implementations-Of-MachineLearning-and-Deep-Learning", "max_issues_repo_head_hexsha": "9e80a56c84073bbf3b5c9d6e8891176e02f0d973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "activation-functions/python-implementations/tanh.py", "max_forks_repo_name": "manojkumar-github/Implementations-Of-MachineLearning-and-Deep-Learning", "max_forks_repo_head_hexsha": "9e80a56c84073bbf3b5c9d6e8891176e02f0d973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5641025641, "max_line_length": 198, "alphanum_fraction": 0.7097020626, "include": true, "reason": "import numpy", "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.9362850026367634, "lm_q1q2_score": 0.9013363998266865}} {"text": "from sympy import *\nimport matplotlib.pyplot as plt\nimport numpy as np\n# For a certain​ automobile, Upper M(x), represents the miles per gallon obtained at a speed of x miles per hour.\n\nx = symbols( 'x' )\nM = -.015 * x**2 + 1.36*x - 7.2 # 30 <= x <= 60\n#M = -0.015 * x**2 + 1.44*x - 7.1 # 30 <= x <= 60\ndM = diff( M, x )\n\ncritical_values = solve( dM, x )\n\ng_xlim = [ 30, 60 ]\nlam_m = lambdify( x, M, np )\n\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 10000, endpoint=True )\ny_vals = lam_m( x_vals )\n\nmin_val = g_xlim[ 0 ]\nmin = M.subs( { x: min_val } )\n# (Type an integer or decimal rounded to the nearest thousandth as​ needed.)\nprint( 'Absolute Minimum MPG is {0} at {1} mph'.format( round( min, 3 ), round( min_val ) ) )\n\nmax_val = critical_values[ 0 ]\nmax = M.subs( { x: max_val } )\n# (Type an integer or decimal rounded to the nearest thousandth as​ needed.)\nprint( 'Absolute Maximum MPG is {0} at {1} mph'.format( round( max, 3 ), round( max_val ) ) )\n\nplt.plot( x_vals, y_vals, label = '' )\nplt.show()", "meta": {"hexsha": "76762087a32d1fd91ab1cbb9577b52e7590a3a59", "size": 1007, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/Classes/MSDS400/Quiz/III/15.py", "max_stars_repo_name": "bmoretz/Python-Playground", "max_stars_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Classes/MSDS400/Quiz/III/15.py", "max_issues_repo_name": "bmoretz/Python-Playground", "max_issues_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Classes/MSDS400/Quiz/III/15.py", "max_forks_repo_name": "bmoretz/Python-Playground", "max_forks_repo_head_hexsha": "a367ec7659b85c24363c21b5c0ac25db08ffa1f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5666666667, "max_line_length": 113, "alphanum_fraction": 0.6405163853, "include": true, "reason": "import numpy,from sympy", "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9825575183283513, "lm_q2_score": 0.9173026652376182, "lm_q1q2_score": 0.9013026303118564}} {"text": "import math\nfrom math import sqrt\nimport numbers\nimport matrix as m\nimport numpy as np\n\ndef zeroes(height, width):\n \"\"\"\n Creates a matrix of zeroes.\n \"\"\"\n g = [[0.0 for _ in range(width)] for __ in range(height)]\n return Matrix(g)\n\ndef identity(n):\n \"\"\"\n Creates a n x n identity matrix.\n \"\"\"\n I = zeroes(n, n)\n for i in range(n):\n I.g[i][i] = 1.0\n return I\n\nclass Matrix(object):\n\n # Constructor\n def __init__(self, grid):\n self.g = grid\n self.h = len(grid)\n self.w = len(grid[0])\n\n #\n # Primary matrix math methods\n #############################\n \n def determinant(self):\n \"\"\"\n Calculates the determinant of a 1x1 or 2x2 matrix.\n \"\"\"\n if not self.is_square():\n raise(ValueError, \"Cannot calculate determinant of non-square matrix.\")\n if self.h > 2:\n raise(NotImplementedError, \"Calculating determinant not implemented for matrices largerer than 2x2.\")\n \n # TODO - your code here\n if self.h == 1:\n \n return self.g[0][0]\n if self.h == 2:\n \n return self.g[0][0]*self.g[1][1]-self.g[0][1]*self.g[1][0]\n \n \n def trace(self):\n \"\"\"\n Calculates the trace of a matrix (sum of diagonal entries).\n \"\"\"\n if not self.is_square():\n raise(ValueError, \"Cannot calculate the trace of a non-square matrix.\")\n \n # TODO - your code here\n summ=0\n for i in range(len(self.g)):\n for j in range(len(self.g[0])):\n if i == j:\n summ+=self.g[i][j]\n \n return summ\n \n def inverse(self):\n \"\"\"\n Calculates the inverse of a 1x1 or 2x2 Matrix.\n \"\"\"\n if not self.is_square():\n raise(ValueError, \"Non-square Matrix does not have an inverse.\")\n if self.h > 2:\n raise(NotImplementedError, \"inversion not implemented for matrices larger than 2x2.\")\n\n # TODO - your code here\n inverse = []\n \n det = Matrix.determinant(self)\n if len(self.g)==1 or len(self.g[0])==1:\n inverse.append([1/self.g[0][0]])\n \n if len(self.g)==2 or len(self.g[0])==2:\n inverse = ([self.g[1][1]/det,-1*self.g[0][1]/det],[-1*self.g[1][0]/det,self.g[0][0]/det])\n invers = m.Matrix(inverse)\n return invers\n\n def T(self):\n \n matrix_transpose = [[0 for y in range(len(self.g))]for x in range(len(self.g[0]))]\n #matrix_transpose = np.zeros((len(matrix[0]),len(matrix)))\n #matrix_transpose = []\n # print(len(matrix))\n # print(len(matrix[0]))\n for i in range(len(self.g)):\n for j in range(len(self.g[0])): \n matrix_transpose[j][i] = self.g[i][j]\n matrixTrans = m.Matrix(matrix_transpose) \n return matrixTrans\n\n def is_square(self):\n return self.h == self.w\n\n #\n # Begin Operator Overloading\n ############################\n def __getitem__(self,idx):\n \"\"\"\n Defines the behavior of using square brackets [] on instances\n of this class.\n\n Example:\n\n > my_matrix = Matrix([ [1, 2], [3, 4] ])\n > my_matrix[0]\n [1, 2]\n\n > my_matrix[0][0]\n 1\n \"\"\"\n return self.g[idx]\n\n def __repr__(self):\n \"\"\"\n Defines the behavior of calling print on an instance of this class.\n \"\"\"\n s = \"\"\n for row in self.g:\n s += \" \".join([\"{} \".format(x) for x in row])\n s += \"\\n\"\n return s\n\n def __add__(self,other):\n \"\"\"\n Defines the behavior of the + operator\n \"\"\"\n if self.h != other.h or self.w != other.w:\n raise(ValueError, \"Matrices can only be added if the dimensions are the same\") \n # \n # TODO - your code here\n #\n \n # initialize matrix to hold the results\n matrixSum = []\n\n # matrix to hold a row for appending sums of each element\n row = []\n\n # TODO: write a for loop within a for loop to iterate over\n # the matrices\n for i in range(len(self.g)):\n row=[]\n for j in range(len(self.g[0])):\n # TODO: As you iterate through the matrices, add matching\n # elements and append the sum to the row variable \n row.append(self.g[i][j]+other.g[i][j])\n # TODO: When a row is filled, append the row to matrixSum. \n # Then reinitialize row as an empty list\n matrixSum.append(row)\n matrixSummation = m.Matrix(matrixSum)\n return matrixSummation\n\n def __neg__(self):\n \"\"\"\n Defines the behavior of - operator (NOT subtraction)\n\n Example:\n\n > my_matrix = Matrix([ [1, 2], [3, 4] ])\n > negative = -my_matrix\n > print(negative)\n -1.0 -2.0\n -3.0 -4.0\n \"\"\"\n # \n # TODO - your code here\n #\n matrixNeg = []\n\n # matrix to hold a row for appending sums of each element\n row = []\n\n # TODO: write a for loop within a for loop to iterate over\n # the matrices\n for i in range(len(self.g)):\n row=[]\n for j in range(len(self.g[0])):\n # TODO: As you iterate through the matrices, add matching\n # elements and append the sum to the row variable \n row.append(-1*self.g[i][j])\n # TODO: When a row is filled, append the row to matrixSum. \n # Then reinitialize row as an empty list\n matrixNeg.append(row)\n matrixNegative = m.Matrix(matrixNeg)\n return matrixNegative\n\n def __sub__(self, other):\n \"\"\"\n Defines the behavior of - operator (as subtraction)\n \"\"\"\n # \n # TODO - your code here\n #\n # initialize matrix to hold the results\n matrixSub = []\n\n # matrix to hold a row for appending sums of each element\n row = []\n\n # TODO: write a for loop within a for loop to iterate over\n # the matrices\n for i in range(len(self.g)):\n row=[]\n for j in range(len(self.g[0])):\n # TODO: As you iterate through the matrices, add matching\n # elements and append the sum to the row variable \n row.append(self.g[i][j]-other.g[i][j])\n # TODO: When a row is filled, append the row to matrixSum. \n # Then reinitialize row as an empty list\n matrixSub.append(row)\n matrixSubtract = m.Matrix(matrixSub)\n return matrixSubtract\n \n def __mul__(self, other):\n \"\"\"\n Defines the behavior of * operator (matrix multiplication)\n \"\"\"\n # \n # TODO - your code here\n #\n \n product = []\n current_rowA = []\n current_rowB = []\n Other = m.Matrix(other.g)\n transB = Other.T()\n row_results=[]\n for i in range(len(self.g)):\n for j in range(len(other.g[0])):\n result=0\n current_rowA=self.g[i]\n current_rowB=transB[j]\n for k in range(len(current_rowB)):\n result += current_rowA[k]*current_rowB[k]\n row_results.append(result)\n product.append(row_results)\n row_results=[]\n matrixMul = m.Matrix(product)\n return matrixMul\n \n def __rmul__(self, other):\n \"\"\"\n Called when the thing on the left of the * is not a matrix.\n\n Example:\n\n > identity = Matrix([ [1,0], [0,1] ])\n > doubled = 2 * identity\n > print(doubled)\n 2.0 0.0\n 0.0 2.0\n \"\"\"\n matrixRmul = []\n\n # matrix to hold a row for appending sums of each element\n row = []\n\n # TODO: write a for loop within a for loop to iterate over\n # the matrices\n for i in range(len(self.g)):\n row=[]\n for j in range(len(self.g[0])):\n # TODO: As you iterate through the matrices, add matching\n # elements and append the sum to the row variable \n row.append(other*self.g[i][j])\n # TODO: When a row is filled, append the row to matrixSum. \n # Then reinitialize row as an empty list\n matrixRmul.append(row)\n matrixRmult = m.Matrix(matrixRmul)\n return matrixRmult\n \n if isinstance(other, numbers.Number):\n pass\n # \n # TODO - your code here\n #\n ", "meta": {"hexsha": "ac4674a5b8de4d72778c1029fe5c8349277c9afe", "size": 8728, "ext": "py", "lang": "Python", "max_stars_repo_path": "matrix.py", "max_stars_repo_name": "BabakShah/SDC-KalmanFilter", "max_stars_repo_head_hexsha": "fdf246795268d40226109d040ad5dcc058fc1a3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix.py", "max_issues_repo_name": "BabakShah/SDC-KalmanFilter", "max_issues_repo_head_hexsha": "fdf246795268d40226109d040ad5dcc058fc1a3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix.py", "max_forks_repo_name": "BabakShah/SDC-KalmanFilter", "max_forks_repo_head_hexsha": "fdf246795268d40226109d040ad5dcc058fc1a3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2006920415, "max_line_length": 113, "alphanum_fraction": 0.5095096242, "include": true, "reason": "import numpy", "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714922, "lm_q2_score": 0.9263037241905732, "lm_q1q2_score": 0.9007513767525873}} {"text": "#autor: Rodolfo Quispe\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#define the original function\ndef f(x, w):\n return w[0]*(x**3) + w[1]*(x**2) + w[2]*(x) + w[3]\n\n#define squared sum as cost function\ndef cost(calculated_y, expected_y):\n return ((expected_y - calculated_y)**2).sum()\n\n#given the weights w (a, b, c, d), x \n#and y (training data), compute gradient \ndef gradient(x, y, w):\n fact = np.vstack( (x*x*x, x*x, x , np.ones(len(x))) )\n return 2 * (f(x, w) - y) * fact\n\n# define the update function delta w\ndef delta_w(w_k, x, t, learning_rate):\n return learning_rate * gradient(x, t, w_k).sum(axis = 1)\n\ndef plot_results(x, y, w): \n fig = plt.figure(figsize=(12, 6))\n fig.add_subplot(111)\n \n # Plot the target t versus the input x\n plt.plot(x, y, 'o', label='data')\n # Plot the initial line\n x = list(range(-10, 10))\n plt.plot(x, [f(i,w) for i in x],'g-',label='f(x)')\n\n #set extra plot parameters\n plt.title('Question 2: Gradient Descent with learning rate 1e-4')\n plt.xlim(-6,6)\n plt.ylim(-60,60)\n plt.xlabel('x')\n plt.ylabel('f(x)', fontsize=15)\n plt.legend(loc=2)\n plt.grid()\n\n plt.show()\n fig.savefig(\"t01_2.png\")\n\nif __name__ == \"__main__\":\n\n x_train = np.array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5])\n y_train = np.array([-53.9, -28.5, -20.7, -3.6, -9.8, 5.0, \n 4.2, 5.1, 11.4, 27.4, 44.0])\n\n\n # Set the initial weight parameter\n w = np.array([0, 0, 0, 0])\n # Set the learning rate\n learning_rate = 1.0e-4\n\n #number of gradient descent iterations\n nb_of_iterations = 50 \n \n # Start performing the gradient descent updates, \n # and print the weights and cost:\n \n # Lists to store the weight,costs values\n w_cost = [ cost(f(x_train, w), y_train)]\n w_status = [w]\n for i in range(nb_of_iterations):\n #Get the delta w update\n dw = delta_w(w, x_train, y_train, learning_rate)\n #Update the current weight parameter\n w = w - dw\n #Add weight,cost to lists\n w_cost.append(cost(f(x_train, w), y_train))\n w_status.append(w)\n\n print ('iterations', nb_of_iterations)\n print ('cost', w_cost[-1])\n print ('best parameters', w_status[-1])\n plot_results(x_train, y_train, w_status[-1])\n", "meta": {"hexsha": "777afdf2369fd280d2293200a82eabdf32d70471", "size": 2194, "ext": "py", "lang": "Python", "max_stars_repo_path": "t1/t01_2.py", "max_stars_repo_name": "RQuispeC/Machine-Learning", "max_stars_repo_head_hexsha": "79d0e25889d8e1149fa39e4af0cdf16cc94019af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "t1/t01_2.py", "max_issues_repo_name": "RQuispeC/Machine-Learning", "max_issues_repo_head_hexsha": "79d0e25889d8e1149fa39e4af0cdf16cc94019af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t1/t01_2.py", "max_forks_repo_name": "RQuispeC/Machine-Learning", "max_forks_repo_head_hexsha": "79d0e25889d8e1149fa39e4af0cdf16cc94019af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7721518987, "max_line_length": 67, "alphanum_fraction": 0.6271649954, "include": true, "reason": "import numpy", "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.965899577232538, "lm_q2_score": 0.9324533130837862, "lm_q1q2_score": 0.9006562608967086}} {"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\nfrom lib.printer import printer\n\n\ndef func(x):\n return np.exp(x)\n\n\ndef trapezoidal(a, b, y=None, N=10, f=func):\n integral = 0\n x = np.linspace(a, b, N + 1)\n if y is None:\n y = f(x)\n y = np.array(y)\n l = len(y)\n if len(x) != len(y):\n raise ValueError(\"length of x must be same as y\")\n for i in range(len(x)):\n if i == 0 or i == len(x) - 1:\n integral += y[i]\n else:\n integral += 2 * y[i]\n integral *= (b - a) / (2 * N)\n\n # Alternatively,\n \"\"\"\n y_1=y[:l-1:2]\n y_2=y[1:l:2]\n\n integral = (b-a)/(N*2) * (np.sum(y_1 + y_2))\n \"\"\"\n return integral\n\n\ndef simpson(a, b, y=None, N=10, f=func):\n integral = 0\n x = np.linspace(a, b, N + 1)\n if y is None:\n y = f(x)\n y = np.array(y)\n l = len(y)\n if len(x) != l:\n raise ValueError(\"length of x must be same as y\")\n\n for i in range(len(x)):\n if i == 0 or i == len(x) - 1:\n integral += y[i]\n elif i % 2 == 0:\n integral += 2 * y[i]\n else:\n integral += 4 * y[i]\n\n integral *= (b - a) / (N * 3)\n # Alternatively,\n \"\"\"\n y_1=y[:l-2:2]\n y_2=y[1:l-1:2]\n y_3=y[2:l:2]\n\n integral = (b-a)/(N*3) * (np.sum(y_1 + 4*y_2 + y_3))\n \"\"\"\n return integral\n\n\ndef integration(a, b, ni, function=None):\n trueval = integrate.quad(function, a, b)\n trapval = trapezoidal(a, b, N=ni, f=function)\n simpval = simpson(a, b, N=ni, f=function)\n\n # PRINTING\n printer(\n np.array(\n [\n [\"Method used\", \"Integral\", \"Error constant \"],\n [\"Quad method scipy\", trueval[0], trueval[1]],\n [\"Trapezoidal rule\", trapval, trueval[1] - (trapval - trueval[0])],\n [\"Simpson's rule\", simpval, trueval[1] - (simpval - trueval[0])],\n ]\n )\n )\n\n # PLOTTING CONVERGENCE GRAPH\n\n y_data_2, y_data, y_data_3 = [], [], []\n n_array = np.arange(40, 370, 2)\n h_array = (b - a) / n_array\n\n for n in n_array:\n x_data = np.linspace(a, b, n + 1)\n y_data.append(trapezoidal(a, b, N=n, f=function))\n y_data_2.append(simpson(a, b, N=n, f=function))\n y_data_3.append(integrate.simpson(func(x_data), x_data))\n\n plt.xscale(\"log\")\n plt.plot(h_array, y_data, label=\"Trapezoidal rule\")\n plt.scatter(h_array, y_data, label=\"Trapezoidal rule\")\n plt.plot(h_array, y_data_2, label=\"Simpson's rule\")\n plt.scatter(h_array, y_data_2, label=\"Trapezoidal rule\")\n plt.plot(h_array, y_data_3, linestyle=\"--\", label=\"scipy's simpson implementation\")\n plt.legend()\n\n\nif __name__ == \"__main__\":\n\n # n=int(input(\"Enter the number of sub-intervals : \"))\n # a=int(input(\"Enter the lower-limit(a) : \"))\n # b=int(input(\"Enter the upper-limit(b) : \"))\n \"\"\"\n PART 3(a)\n \"\"\"\n V = [0, 0.5, 2.0, 4.05, 8, 12.5, 18, 24.5, 32, 40.5, 50]\n trapval = trapezoidal(0, 1, y=V, N=10)\n simpval = simpson(0, 1, y=V, N=10)\n\n printer(\n np.array([[\"Trapezoidal rule\", trapval], [\"Simpson's rule\", simpval]]),\n column=False,\n )\n\n \"\"\"\n PART 3(b)\n https://github.com/scipy/scipy/blob/v1.7.1/scipy/integrate/_quadrature.py#L433-L555\n \"\"\"\n integration(0, 13, 100, function=func)\n plt.show()\n", "meta": {"hexsha": "903c172541f1c33c83ea3d541574e04121b867c5", "size": 3351, "ext": "py", "lang": "Python", "max_stars_repo_path": "newton_cotes.py", "max_stars_repo_name": "plancky/mathematical_physics_II", "max_stars_repo_head_hexsha": "c912dca1a58c218ddb06dc6cbca021b03a703540", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newton_cotes.py", "max_issues_repo_name": "plancky/mathematical_physics_II", "max_issues_repo_head_hexsha": "c912dca1a58c218ddb06dc6cbca021b03a703540", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newton_cotes.py", "max_forks_repo_name": "plancky/mathematical_physics_II", "max_forks_repo_head_hexsha": "c912dca1a58c218ddb06dc6cbca021b03a703540", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1796875, "max_line_length": 87, "alphanum_fraction": 0.533572068, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.9353465143471483, "lm_q1q2_score": 0.9004329423817216}} {"text": "#sympy \n\nfrom pylab import * \nimport sympy as sp \n\n\nprint(pi) \nprint(sp.pi) \n\n#there is a symbolic pi, which we can evaluate using the evalf method. \n\n#get 32 digits of pi \nprint(sp.pi.evalf(32))\n\n#There are other kinds of numeric objects \n\np = sp.Rational(3,7) \nq = sp.Rational(2,3) \nprint(p+q)\nprint(p*q) \n\n#when dealing with symbolic results, things can get ugly \nprint(sp.integrate('x*sin(3/x)'))\n\n#that is ugly. Sympy has a \"pretty print\" function. \nsp.pprint(sp.integrate('x*sin(3/x)'))\n\n#In general, we want to use symbolic variables. \nsp.var('x,y') \nsp.pprint(x/2) \n\n\n#now we can define expressions in terms of symbolic variables. \ns = x*sp.sin(3/x) \n\n#Now we can evaluate this expression anywhere. \nprint(s.subs(x,pi))\n\n#kcooper does song and dance between 'f' and 'f(x)' \n#f(x) is NOT a function, it's the value of the function. It's the value of function \n# f is just the function and is a rule for mapping one input to another. \n#function you give it an input and get an output. \n#s is just an expression and is a collection of symbols you cannot do s(x) \nprint(s.subs(x,pi).evalf(50))\n\n\n#We have noted that s is an expression. Let's make a function. \n\nt = lambda x: x*sp.sin(3/x) \n\n#y is a symbolic variable. \n#Note now the difference between the expression s and the function t \nsp.pprint(s(y))\nsp.pprint(t(y))\n\n#Now let's define a new expression. \n#don't care about 64.0 or anything because they are just symbolic numbers and we could use evalf() to evalute to arbitrary precision \nu = 64*x**4-100*x**3 + 22*x**2 - 65*x+4\n\n#didn't have to tell him how many points to choose or anything. \nsp.plot(u,(x,-.5,1.5))\n#sympy plot doesn't need the show() command \n\n3h = arange(-0.5,1.5,0.001)\n\nh = (1.5 -(-.5))/1000.0 \nx_vec = arange(-.5,1.5+h,h)\n\nu_vec = zeros(len(x_vec))\n\n#have to evaluate u at 1001 points. \nfor i in arange(len(x_vec)): \n\tu_vec[i] = u.subs(x, x_vec[i])\n\nplot(x_vec, u_vec)\nshow() \n\n\n#***********************************NOVEMBER 30TH LECTURE NOTES ******************************* \n\n#trying to find the root of the polynomial. K Cooper designed it to have the root at x = 1/16 \nprint(u.subs(x,sp.Rational(1,16)))\nfirst_root = sp.Rational(1,16) \n\nv = sp.simplify(u / (x-first_root))\nsp.pprint(v)\n\n\n#simplify always checks to divide out polynomial factors, and execute trig identities. \n#x^2 + 2x + 1 is a perfect square. \nsp.pprint((x**2 + 2*x + 1) / (x + 1) )\nsp.pprint(sp.simplify((x**2 + 2*x + 1) / (x + 1)))\nsp.pprint((sp.sin(x)**2 + sp.cos(x)**2 / sp.cos(x)))u \n\n\n\n#We can factor polynomials \nsp.pprint(u.factor()) \n\n#we can also expand polynomials \nw = u.factor()\nsp.pprint(w) \nsp.pprint(sp.expand(w)) \n\nsp.var('a')\np = (x -1) * (x-a) * (x +a) \n\nsp.pprint(p.expand().collect(x))\nsp.pprint(p.expand().collect(a))\nsp.pprint(sp.horner(p,x))\n\n#sympy can do calculus \n\n#this limit would be 1 \nsp.pprint(sp.limit(sp.sin(x) / x , x, 0))\n\n#limit would be zero(0) because it's 0 * bounded function \nsp.pprint(sp.limit( x * sp.sin(3/x), x, 0))\n\n#you can take a limit of a limit \nsp.pprint(sp.limit(sp.limit((x**2+1) / (a*x**2 + 2*x + 1), x , sp.oo), a, 97)\n\n#sympy can take derivatives\n#differentiate u with respect to x \nsp.pprint(sp.diff(u,x))\n\n#we can take a second derivative. \nsp.pprint(sp.diff(u,x,2))\n\nu_prime = sp.diff(u,x) \nsp.pprint(u_prime) \n\nu_double_prime = sp.diff(u,x,2)\nsp.pprint(u_double_prime.expand() - sp.diff(u_prime,x))\n\n#the things inside would have to be REAL \narc_length_integrand = sp.sqrt(1 + sp.diff(u,x)**2)\n\narc_length = sp.integrate(arc_length_integrand, (x,0,1)) \n\n#it doesn't know how to evaluate the integral so it'll just print the last known correct answer. \n#but we need to force it to do the integral \nsp.pprint(arc_length)\n\n#can get 10 digits if you want. \narc_length = sp.integrate(arc_length_integrand, (x,0,1)).evalf(10) \nsp.pprint(arc_length) \n\n#more integrals \n#u is a quartic polynomial \nsp.pprint(sp.integrate(u))\n\nsp.pprint(sp.integrate(arc_length) )\n\n#showing to use a tuple going from negative infinity to positive infinity. \n#use .evalf() to make him do it with 20 digits of accuracy. \nsp.pprint(sp.integrate(sp.exp(-x**2), [x,-sp.oo,sp.oo]).evalf(20))\n#solution is sqrt(pi) \n\n# ******************* SERIES **********************88 \n#why do we learn series? because polynomials are what we can evluate on a computer. \n#anything we can write as a series we can integrate. \n\ns = sp.series(sp.sin(x), x)\n\nsp.pprint(s)\n\n#big O denotes what the dominant term is. Exampel is O means that x^6 is the dominant term \n\n#can expand something other than 0. \ns = sp.series(sp.sin(x), x, 3)\n\n#now what if we want 16 terms from the series. \ns = sp.series(sp.sin(x), x, 3, 16) \n\n#this would be expanding around 0 \ns = sp.series(sp.sin(x), x, 0, 16) \n\n#you get a list of ordered terms. We could reconstruct the function by taking the sum of these terms in the list. \nt = s.as_ordered_terms() \n\n#if you give it a negative index it will start at the end. \nt = sum(s.as_ordered_terms()[0:-1])\n \nsp.pprint(t) \n\nh = 0.01 \nx_vec = arange(-1.0, 1.0 + h, h) \n\n#y_vec must be numbers! \ny_vec = zeros(len(x_vec))\n\nfor i in arange(len(x_vec)): \n\ty_vec[i] = t.subs(x, x_vec[i]).evalf()\n\nplot(x_vec, y_vec, x_vec, sin(x_vec)) \nshow()\n\n\n#********************* DECEMBER 4th NOTES *************** \n\n#we could use less terms to make it look worse. \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "2f0731406ab48b92355f6372abae9a390a387c76", "size": 5312, "ext": "py", "lang": "Python", "max_stars_repo_path": "math300/nov_18_sympy.py", "max_stars_repo_name": "johnnydevriese/wsu_courses", "max_stars_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "math300/nov_18_sympy.py", "max_issues_repo_name": "johnnydevriese/wsu_courses", "max_issues_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math300/nov_18_sympy.py", "max_forks_repo_name": "johnnydevriese/wsu_courses", "max_forks_repo_head_hexsha": "b55efd501c2d8f0651891f422a486e32533f5aa0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.036199095, "max_line_length": 133, "alphanum_fraction": 0.6630271084, "include": true, "reason": "import sympy", "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877658567787, "lm_q2_score": 0.9273633011673481, "lm_q1q2_score": 0.9001802109477002}} {"text": "# 6.1 David C. Lay Inner Product\n\n# An inner product is a generalization of the dot product. In a vector space, it is a \n# way to multiply vectors together, with the result of this multiplication being a scalar.\n\n'''\nExample: Compute u.v and v.u for u = col(2, -5, -1), v = col(3, 2, -3)\n\nu.v = transpose(u).v = (3 * 2) + (- 5 * 2) + (-1 * -3) = -1\nv.u = 10 Because u.v = v.u\n'''\n\nu, v = [2, -5, -1], [4, 2, -3]\n\ninner_prod = 0\n\nfor i in range(len(u)):\n inner_prod += u[i] * v[i]\n\nprint(inner_prod)\n\n# numpy library\nimport numpy as np\n\nu = np.array([2, -5, -1]);\nv = np.array([4, 2, -3]);\n\ninner_prod = np.inner(v, u)\n\nprint(inner_prod)\n\n# for 1-d array np.inner(u, v) is same as sum(u[:] * v[:])\n\ninner_prod = sum(u[:] * v[:])\nprint(inner_prod)\n\n# or simply\n\ninner_prod = u * v\ninner_prod = sum(inner_prod)\nprint(inner_prod)\n\nx = np.array([[1], [2]])\nx_trans = np.transpose(x)\nout = np.dot(x_trans, x)\n\nprint(sum(out)[0])\n\n# for multi-dimentional array\na = np.array([[1,2], [3,4]]) \nb = np.array([[11, 12], [13, 14]]) \n\nprint(np.inner(a, b))\n'''\n In the above case, the inner product is calculated as −\n \n 1*11+2*12, 1*13+2*14 \n 3*11+4*12, 3*13+4*14 \n'''", "meta": {"hexsha": "7e32130337bd557ecb3f3576083be2be4032ab01", "size": 1171, "ext": "py", "lang": "Python", "max_stars_repo_path": "linear-algebra/inner-product.py", "max_stars_repo_name": "Nahid-Hassan/code-snippets", "max_stars_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-29T04:09:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:33:36.000Z", "max_issues_repo_path": "linear-algebra/inner-product.py", "max_issues_repo_name": "Nahid-Hassan/code-snippets", "max_issues_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-algebra/inner-product.py", "max_forks_repo_name": "Nahid-Hassan/code-snippets", "max_forks_repo_head_hexsha": "24bd4b81564887822a0801a696001fcbeb6a7a75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T04:55:55.000Z", "avg_line_length": 19.8474576271, "max_line_length": 90, "alphanum_fraction": 0.5892399658, "include": true, "reason": "import numpy", "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.9324533074525658, "lm_q1q2_score": 0.900172853890625}} {"text": "'''\n\nhypothesis\n O^T * x = O0X0 + O1X1 + ... + OmXm\n h(O) = O^T * x\n\ncost function\n cost(h(x), y) = (h(x) - y)^2\n J(O) = (1/2*m) * sum(cost(h(x), y))\n\nfit parameters with gradient descent\n Oj = Oj - learning_rate * partial_derivative(J(O))\n partial_derivative = 1/m * sum((h(xi) - yi) * xij)\n\n'''\n\n\nclass LinearRegression:\n def __init__(self, learning_rate=0.001, iters=10000, fit_intercept=True, theta=None):\n self.learning_rate = learning_rate\n self.iters = iters\n self.fit_intercept = fit_intercept\n self.theta = theta\n\n def __add_intercept(self, X):\n intercept = np.ones((X.shape[0], 1))\n return np.concatenate((intercept, X), axis=1)\n\n def __cost(self, h, y):\n return np.sum((h - y) * (h - y)) / (2*y.size)\n\n def fit(self, X, y):\n if self.fit_intercept:\n X = self.__add_intercept(X)\n\n if self.theta is None:\n self.theta = np.zeros(X.shape[1])\n\n for i in range(self.iters):\n h = np.dot(X, self.theta)\n cost = self.__cost(h, y)\n for j in range(len(self.theta)):\n gradient = np.dot(h-y, X[:, j])\n self.theta[j] = self.theta[j] - (self.learning_rate / y.size * gradient)\n print(cost)\n\n\nif __name__ == '__main__':\n import numpy as np\n hours_studied = np.array([[2], [4], [6], [8], [10], [13], [13.5], [14], [16], [19], [25]])\n grades = np.array([1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5])\n\n print(\"GRADIENT DESCENT\")\n model = LinearRegression()\n model.fit(hours_studied, grades)\n\n '''\n gradients, cost = linear_regression(hours_studied, grades)\n print(gradients)\n print(cost)\n\n predict = lambda x: gradients[1]*x + gradients[0]\n print(predict(21))\n\n '''\n\n '''\n NORMAL EQUATION METHOD\n theta = (X^T * X)^-1 * X^T * y\n '''\n\n print(\"NORMAL EQ\")\n hours_studied_ones = np.concatenate((np.ones((len(hours_studied), 1)), hours_studied), axis=1)\n theta = np.dot(np.dot(np.linalg.inv(np.dot(np.transpose(hours_studied_ones), hours_studied_ones)), np.transpose(hours_studied_ones)), grades)\n model = LinearRegression(theta=theta, iters=1)\n model.fit(hours_studied, grades)\n\n'''\nSHORT SELLING\nABC share 54$\n\nborrow 5 abc shares and sell them for 270$\n\nABC share 45$\n\nbuy 5 abc shares for 225$ and give them back to creditor\n\nprofit = 270$ - 45$ = 25$\n'''", "meta": {"hexsha": "05fb237071c0beb476f83285dc66a1f7bcdf58db", "size": 2392, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml/module_ml/linear_reg.py", "max_stars_repo_name": "matija94/show-me-the-code", "max_stars_repo_head_hexsha": "7e98b15da03712e28417f2c808c4324989ce9bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-10T21:05:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-10T21:05:46.000Z", "max_issues_repo_path": "ml/module_ml/linear_reg.py", "max_issues_repo_name": "matija94/show-me-the-code", "max_issues_repo_head_hexsha": "7e98b15da03712e28417f2c808c4324989ce9bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/module_ml/linear_reg.py", "max_forks_repo_name": "matija94/show-me-the-code", "max_forks_repo_head_hexsha": "7e98b15da03712e28417f2c808c4324989ce9bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8764044944, "max_line_length": 145, "alphanum_fraction": 0.5873745819, "include": true, "reason": "import numpy", "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.9304582603151215, "lm_q1q2_score": 0.9001348639702678}}