$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$becomes $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$ Tex/LaTex however has a bit of learning curve. There are tutorials out there. But now there is WYSIWYG editor too: https://latexeditor.lagrida.com/ You an also use Jupyter Notebook to type equations in similar ways and also run Python right on it too. So if you have math things to tell, now it is easier to display your equations and data charts etc.
Monday, November 11, 2024
MathJax
Thursday, October 31, 2024
Angular revisited
https://angular.dev/tutorials/first-app
Good luck if you must use it.
Wednesday, September 18, 2024
Java ScheduledExecutorService
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ConcurrentStuff { public static void main(String[] args) { System.out.println("begin"); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); System.out.println("scheduling a task to run after 2 seconds"); // Schedule a task to run after a delay of 2 seconds executor.schedule(new MyTask(), 2, TimeUnit.SECONDS); System.out.println("scheduling a task to delay 3 seconds then repeat every 5 seconds"); // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds executor.scheduleAtFixedRate(new MyTask(), 3, 5, TimeUnit.SECONDS); // Wait for scheduled tasks to complete try { System.out.println("sleeping to demo scheduling at work"); Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } // Shutdown the executor executor.shutdown(); System.out.println("end"); } static class MyTask implements Runnable { @Override public void run() { System.out.println("Task executed at: " + new java.util.Date()); } } }
Sunday, September 15, 2024
Determinant of a matrix
public class CodeWar { public static int[][] buildSubmatrix(int[][] matrix, int r, int c) { int size = matrix.length - 1; int result[][] = new int[size][size]; int a = 0, b = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { if (i != 0 && j != c) { result[a][b] = matrix[i][j]; b++; } } if (i != r) { a++; b = 0; } } return result; } public static int determinant(int[][] matrix) { if (matrix.length == 1) return matrix[0][0]; int sign = 1; int sum = 0; for (int i = 0; i < matrix[0].length; i++) { int n = matrix[0][i]; int submatrix[][] = buildSubmatrix(matrix, 0,i); sum += sign * n * determinant(submatrix); sign = sign * -1; } return sum; } public static void main(String arg[]) { int[][] matrix = { { -2, -1,2 }, { 2,1,4 }, { -3,3,1 } }; System.out.println(determinant(matrix)); } }
Tuesday, August 20, 2024
Java: of list and set
public static void main(String arg[]) { String a[] = new String[] { "A", "B", "C", "D", "A", "C", "E" }; List<String> list = Arrays.asList(a); // constructed one way List<String> list2 = List.of(a); // constructed another way (java 9+) List<String> list3 = List.of( "A", "B", "C", "D", "A", "C", "E" ); // yet another way // using stream distinct one way List<String> noDups = list.stream().distinct().collect(Collectors.toList()); // using stream distinct another way List<String> noDups2 = list2.stream().distinct().toList(); // put on a set and make a iist out of it Set<String> set = new LinkedHashSet<>(); set.addAll(list3); List<String> noDups3 = new ArrayList<>(set); System.out.println(noDups); System.out.println(noDups2); System.out.println(noDups3); }
Wednesday, July 24, 2024
Python linear 2x2 system
import matplotlib.pyplot as plt import numpy as np import math """ Simple little 2x2 system example: x + 2y = 1 3x + 5y = 2 This can be written as matrix form [A][x] = [B]: [1 2][x] = [1] [3 5][y] [2] """ A = np.array([[1, 2], [3, 5]]) B = np.array([1, 2]) XMIN, XMAX = -5, 5 YMIN, YMAX = -5, 5 GRIDSIZE = 1 STEPS = 101 a11 = A[0][0]; a12 = A[0][1]; a21 = A[1][0]; a22 = A[1][1]; b11 = B[0]; b12 = B[1]; def f(x): return (-a11*x+b11)/a12 def g(x): return (-a21*x+b12)/a22 x = np.linspace(XMIN,XMAX,STEPS) plt.axis([XMIN,XMAX,YMIN,YMAX]) y1v = np.zeros(len(x)) y2v = np.zeros(len(x)) for i in range(len(x)): try: y1v[i] = f(x[i]) y2v[i] = g(x[i]) except: pass try: solution = np.linalg.solve(A, B) print("Solution") print(solution) solutionpoint = "(${0:.2f}, ${1:.2f})".format(solution[0], solution[1]); plt.plot(solution[0],solution[1],'bo'); # blue circle plt.annotate( solutionpoint,(solution[0],solution[1])); except: print("No solution") eq1 = "{0}x+{1}y={2}".format(a11,a12,b11); eq2 = "{0}x+{1}y={2}".format(a21,a22,b12); plt.plot(x,y1v, color='r',label=eq1) plt.plot(x,y2v, color='g',label=eq2) # make axes plt.axhline(y=0, color='k') # 'k' means black plt.axvline(x=0, color='k') # gca is get current axes plt.gca().set_aspect('equal') plt.gca().set_xticks(np.arange(XMIN,XMAX,GRIDSIZE)) plt.gca().set_yticks(np.arange(YMIN,YMAX,GRIDSIZE)) plt.grid(True) plt.legend() plt.show()
Monday, July 22, 2024
Python linear algebra
import numpy as np """ Simple little 2x2 system example: x + 2y = 1 3x + 5y = 2 This can be written as matrix form [A][x] = [B]: [1 2][x] = [1] [3 5][y] [2] So the solution is inv(A)B Inverse matrix is painful to do by hand, but numpy can do it easy, It even has a solve method """ A = np.array([[1, 2], [3, 5]]) B = np.array([1, 2]) Ainv = np.linalg.inv(A) solution = np.matmul(Ainv,B) print("Solution by multiply inverse: ") print(solution) solution2 = np.linalg.solve(A, B) print("Solution by linalg solve: ") print(solution2)Output:
Solution by multiply inverse matrix and right hand side: [-1. 1.] or by linalg solve: [-1. 1.]That means x=-1, y =1.
Wednesday, July 3, 2024
Python Simple Graphing (part 2)
import matplotlib.pyplot as plt import numpy as np import math def f(x): return math.sin(x) # using 101 steps so I know I get to 0 x = np.linspace(-5,5,101) plt.plot(x,f(x)) plt.show()Error is "TypeError: only length-1 arrays can be converted to Python scalars". What?? Oh that's because this plt.plot() method really takes 2 arrays, the x values and the y values. The following works better
import matplotlib.pyplot as plt import numpy as np import math def f(x): return math.sin(x) # using 101 steps so I know I get to 0 x = np.linspace(-5,5,101) yv = np.zeros(len(x)) for i in range(len(x)): yv[i] = f(x[i]) plt.plot(x,yv) plt.show()This works a little better but I like axes and grids and properly scaled graph! Ok after a little researching here we go:
import matplotlib.pyplot as plt import numpy as np import math XMIN, XMAX = -5, 5 YMIN, YMAX = -5, 5 GRIDSIZE = 1 STEPS = 101 def f(x): return math.sin(x) # using odd steps so I know I get to 0 x = np.linspace(XMIN,XMAX,STEPS) plt.axis([XMIN,XMAX,YMIN,YMAX]) plt.title('my graph') yv = np.zeros(len(x)) for i in range(len(x)): yv[i] = f(x[i]) plt.plot(x,yv) # make axes plt.axhline(y=0, color='k') # 'k' means black plt.axvline(x=0, color='k') # gca is get current axes plt.gca().set_aspect('equal') plt.gca().set_xticks(np.arange(XMIN,XMAX,GRIDSIZE)) plt.gca().set_yticks(np.arange(YMIN,YMAX,GRIDSIZE)) plt.grid(True) plt.show()
Monday, June 10, 2024
Python simple graphing
You first need to install it:.
pip3 install matplotlib
Here is some simple code. x range from -5,5. plot y=x2+1
import matplotlib.pyplot as plt import numpy as np x = np.arange(-5,5,0.1) y = x*x+1 plt.plot(x,y) plt.show()Although this works but it seems wacky scale. And let me try some other function, let's give it tricky function y=1/x: Eeew this is ugly (and wrong) This can be fixed if I change x to x = np.linspace(-5,5,100). See documentation here: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html But eew, it is not what I expect it to do at x=0? First do a step with odd number so you know 0 gets evaluated, then make your function a little method, and have an extra with statement to ignore bad output
import matplotlib.pyplot as plt import numpy as np def f(x): with np.errstate(divide='ignore', invalid='ignore'): return 1/x # using 101 steps so I know I get to 0 x = np.linspace(-5,5,101) plt.plot(x,f(x)) plt.show()Ok a few lines give you much functionality... but less than super smooth if you ask me... There are many ways to supply that x range. and many ways to tweak graph like add axes, colors, labels, etc.
Monday, May 20, 2024
Python OOP: a quick look
class Car: def __init__(self, name): self.name=name make="" model=""Do I need to define some private fields first and do some get/set stuff, and then get tired of it and use lombok? No you don't. Do I even need pre-define my variables in constructor? No I don't because you define variables on the fly in Python. Ok I put it in a file Car.py. How do I load it in the prompt?
import Car. Ok it let me. but how about
mycar = Car("mycar")boom get an error. I need to do
from Car import *Ok did that now I can do mycar("mycar"). Ok let's set some make and models.
mycar.make="Toyota" mycar.model="Corolla"So far so good. What about setting an undefined field like this?
mycar.year=2020Oh no errors, it let you do it! I guess I have to get used to the define variables and even fields on the fly. So you better make sure you type correctly. Waita minute, no public, private, protected? Did any OO aficiondos jump forward to blast Python? Is there things like reflective api to figure out what fields you have? There is this
dir(mycar)to tells me what fields I have. "dir" is so DOS! There is a neato
vars(mycar)to tell me what fields and values I got so far. Ok, inheritance, no interface and "implements" vs "extends" differences as in Java. How about "abstract" as in C++? (There is. It is called the ABC) Oh you can even do multiple inheritance! (not worrying about the diamond problem here). What about static (instance) stuff? Yes there is. The variables on the constructor are instance attributes and those outside are class attributes. This is like a lot simpler (but is it better?) than other languages. Typos can be hairpulling as you can define variables on the fly. Let me add a little method to make it tell me what we have
def showinfo() : print ("Car "+ name+" is a "+make+" "+model)Boom it does not work!
>>> mycar.showinfo() Traceback (most recent call last): File "<stdin>", line 1, inWhat do you mean 1 was given, I didn't give you any arguments! (now that's an argument with the intepreter). and it turns out it needs a "self" argument. It does not know about itself! This worked:TypeError: showinfo() takes 0 positional arguments but 1 was given
def showinfo(self): print ("Car "+self.name+" is a "+self.make+" "+self.model)Now to call it it is still mycar.showinfo(), no argument passed. Also, "self" is not a reserved word like "this" in C++/java, (or "self" or "me" like other languages). Anything goes but required. This also worked:
def showinfo(foofoo): print ("Car "+foofoo.name+" is a "+foofoo.make+" "+foofoo.model)You just have to provide a dummy variable here. Jeez now that's wacky. I already tolerated the required tabs instead of blocks. Plenty of tutorials about OOP out there such as this https://realpython.com/python3-object-oriented-programming/.
Thursday, May 9, 2024
Python revisited: a little web app
pip3 install flask --upgradeThen I have a little code like this:
from flask import Flask, render_template app = Flask(__name__) @app.get("/") def index(): return "this is home" @app.get("/page1") def page1(): return "<h1>hello</h1><br/>This is like a <i>servlet</i>" @app.get("/page2") def page2(): return render_template("mypage.html",name="Johnny") if __name__=="__main__": app.run()This gives you 3 pages, the main page "/", "/page1", and "/page2" This is the local url: http://127.0.0.1:5000/ And python warned me this is just a development server, a toy. The first two methods are straightforward... you have to punch in html that you are returning. Mixing html and code is nightmare from the original java servlet days like 1990s. It is hard to do a full blown web page even with the triple quote Python string isn't it? The 3rd method is loading a templated file, which resides in my "templates" folder, it can take variables from the caller too: mypage.html looks like this:
<h1>Hi {{name}}</h1> This is a <i>simple</i>, but dynamic HTML page. <p/> {% for i in range(5) %} This is like jsp<br/> {% endfor %}This template file is html intermixed with code. and you can have loops and stuff too! Intermixing html and code can be difficult to maintain. This reminds me of Java Server Pages (which I think nobody uses nowadays) This is a very simple example. Simple examples work better than complex examples for beginners. And that endfor above tells you that blocks are actually good thing.
Wednesday, May 1, 2024
Math Notes: Parabola
The graph looks like this. You can simply plug some points to see the curve of the graph. Or pull out your graphing calculator:
There is a minimum or maximum y value for a parabola, at a point called the vertex. In this parabola the vertex at (0,0). If a is negative you have a upside-down parabola.If you rewrite the equation in this vertex form: y = a(x-h)2+k, you have a parabola with vertex on (h,k).
Finding the vertex
Given the standard form, the x-coordinate of the vertex is given byx = -b/2a |
This is a result of the quadratic formula. x = -b/2a is exactly in the middle of the 2 solutions and is the x-coordinate of the vertex. For the y-coordinate, just plug the x coordinate in and solve for y.
[Insert Example]
The parabola actually has an geometric definition, defined based on a straight line (called the directrix) and a point (called the focus). Definition A parabola is the set of all the points equal distant from a focus point to the directrix line. Let d be the common distance from the focus to the parabola and from the parabola to the directrix line. The vertex is an obvious point on the parabola, on the line of symmetry, exactly in the middle between the focus and the directrix with d here being the smallest. Let's call this distance f, the focal length. The focal length determines the shape of the parabola. The distance from the vertex to the focus is f. From the vertex to the directrix is also f. For simplicity, let the directrix be at y = -f and focus at (0,f). and freeze one frame for a moment at any P at (x,y). [insert picture] Then the vertical red line has length of y + f. Then from P to the Focus, by the distance formula, the length is sqrt( (y - a)2 + x2). They must be equal: sqrt( (y - f)2 + x2) = y + f(y - f)2 + x2 = (y + f)2
y2 - 2fy + f 2 + x2 = y2 + 2fy + f 2
The y2 and f 2 cancel, bring the - 2fy to the right hand side, leaving:
x2 = 4 f y |
Or
y = 1/(4f) x2 |
Latus Rectum
The latus rectum is the line segment parallel to the directrix that goes through the focus with endpoints on the parabola.And the length of the latus rectum is 4f. Here is why:
At the right endpoint of the latus rectum, y = f. Let's solve for x so we know half the length of the latus rectum. Plug that in: x2 = 4f 2. So x = 2f. The right endpoint is (2f,f). The left endpoint is (-2f, f). So length of the latus rectum is 4f.Vertex-Focal Length Form
The equation y = 1/(4f) x2 is the simple case where the vertex at (0,0). For general case, the vertex at (h,k) form is:(x - h)2 = ± 4 f (y - k) |
(y - h)2 = ± 4 f (x - k) |
When you are given a parabola in standard form, it is only straight forward to find the x-coordinate of the vertex which is x = -b/2a. It is not so straight forward to find the focus or the directrix.
However, you can rewrite the standard form into the vertex form (by completing square), so you can read off both coordinates of the vertex (h, k) and calculate the focal length f. With the focal length, you can find the directrix line and the focus point, which is just a focal length away from the vertex. The x-coordinate of the focus will be same as the vertex's x-coordinate. Each end of the latus rectum is 2 focal lengths away from the focus, with same y-coordinate as the focus. [Insert Example]Monday, March 25, 2024
java Timer
import java.util.TimerTask; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.Timer; class HelloWorld { private static class MyTimerTask extends TimerTask { String someValue; MyTimerTask(String someValue) { this.someValue = someValue; } @Override public void run() { System.out.println("Timer run " + someValue); } } public static void main(String[] args) { HelloWorld me = new HelloWorld(); LocalDateTime someTimeLater = LocalDateTime.now().plusSeconds(3); Date futureDate1 = Date.from(someTimeLater.atZone(ZoneId.systemDefault()).toInstant()); System.out.println("Scheduling something to be run in future..."); new Timer().schedule(new MyTimerTask("hello my friend"), futureDate1); System.out.println("going on with my life"); } }
Saturday, January 27, 2024
How many diagonals does a polygon have?
n! --------- - n 2! (n-2)! n (n-1) = ------- - n 2 = n^2-n - 2n ---------- 2 = n^2 - 3n -------- 2 = n(n-3) ------ 2So there are 13(13-3)/2 = 65 diagonals for the 13-gon. This formula n(n-3)/2 I'd keep it in my treasure chest where I put other not-so-obvious formulas like volumne/surface area of a sphere, volume of a pyramid, etc. Waita minute, although my initial observation is not going anywhere but somewhat of a good start. For each point on the polygon, do not count the 2 neighbors including the point itself, so n-3 diagonals for each point. Go around each point of the polygon, so it is n(n-3), but by that time you would have counted twice the number of diagonals, so divide by 2. There you are: n(n-3)/2.