Skip to content

Instantly share code, notes, and snippets.

@joshuachris2001
Last active March 13, 2025 02:07
Show Gist options
  • Save joshuachris2001/ed0dc62e90addef8c43433ca8a13e7c4 to your computer and use it in GitHub Desktop.
Save joshuachris2001/ed0dc62e90addef8c43433ca8a13e7c4 to your computer and use it in GitHub Desktop.
simpledectofrac
from math import *
f = lambda x: 13* sin(x)-12
driv_f = lambda x: 13*cos(x)
starting_point = -4
_loop_limits = 20
_loop_snap_shot = 5
_ans = starting_point - ( f(starting_point) / driv_f(starting_point))
for loop in range(_loop_limits):
_ans = _ans - ( f(_ans) / driv_f(_ans) )
if (loop % _loop_snap_shot) == 0:
print("loop snap",loop,'\n',_ans)
print("final loop",'\n',_ans)
import math
from math import pi
def _decToFrac():
decimal = float(input("Enter a decimal number to convert to a fraction: "))
# Handle negative numbers
is_negative = decimal < 0
decimal = abs(decimal)
# Tolerance for stopping the algorithm
#tolerance = 1e-10
#max_denominator = 1000000 # To prevent excessively large denominators
numerator, denominator = continued_fraction(decimal)#, tolerance, max_denominator)
if is_negative:
numerator = -numerator
#print(f"The decimal {decimal} as a simplified fraction is {numerator}/{denominator}")
print("The decimal " + str(decimal) + " as a simplified fraction is\n " + str(numerator)+"/"+str(denominator))
# backup brute forcing
def brute_continued_fraction(_x, tolerance = 1e-5, max_denominator = 1000):
_is_neg = False
if (_x < 0):
_is_neg = True
_x = abs(_x)
current_numerator, current_denominator = max_denominator, max_denominator
for x in range(1,max_denominator):
for y in range(1,max_denominator):
D = x / y
if abs(D - _x) <= tolerance and y < current_denominator:
current_numerator = x
current_denominator = y
if (_is_neg):
current_numerator*=-1
return current_numerator, current_denominator
assert brute_continued_fraction(-0.5,max_denominator = 10) == (-1,2)
assert brute_continued_fraction(0.5,max_denominator = 50) == (1,2)
def _decimal_to_continued_fraction(x, tolerance=1e-2, max_terms=400):
cf = []
sign = -1 if x < 0 else 1
x = abs(x)
for _ in range(max_terms):
term = math.floor(x)
cf.append(term)
remainder = x - term
if remainder < tolerance:
break
try:
x = 1 / remainder
except ZeroDivisionError:
break
if cf:
cf[0] *= sign # Apply sign to first term
cf[0]
#print(cf)
return cf
def _continued_fraction_to_fraction(cf):
if not cf:
return 0, 1
numerator = 1
denominator = cf[-1]
for term in reversed(cf[:-1]):
numerator, denominator = denominator, term * denominator + numerator
return (denominator, numerator) if len(cf) % 2 == 0 else (denominator, numerator)
def _continued_fraction(dec):
cf = _decimal_to_continued_fraction(dec)
n, d = _continued_fraction_to_fraction(cf)
#print(n,d)
return n, d
def __continued_fraction(x, tolerance=1e-9, max_denominator=1000000):
"""Finds the fraction approximation for x using continued fractions."""
from math import floor
# Handle exact integers
if x == int(x):
return int(x), 1
a0 = floor(x)
h1, k1 = 1, 0 # Numerators and denominators for previous two convergents
h0, k0 = a0, 1
x = x - a0 # Fractional part of x
if x == 0:
return h0, k0
while True:
x = 1 / x
a = floor(x)
x = x - a
h2 = a * h0 + h1
k2 = a * k0 + k1
if k2 > max_denominator:
break
approx = h2 / k2
actual = (h0 + h1 / k1) / (k0 + k1 / k1)
#try:
# actual = (h0 + h1 / k1) / (k0 + k1 / k1)
#except Exception as e:
# actual = (h0 + h1 / (k1+1)) / (k0 + k1 / (k1+1))
error = abs(approx - actual)
if error < tolerance:
break
h1, k1 = h0, k0
h0, k0 = h2, k2-1
if x == 0 or abs(x) < tolerance:
break
print(h0, k0)
return h0, k0
assert _continued_fraction(0.5) == (1,2)
assert _continued_fraction(0.3333) == (1,3)
assert _continued_fraction(0.666666) == (2,3)
def to_frac(dec):
return _continued_fraction(dec)
from math import*
from turtle import*
speed(10)
hideturtle()
width(2)
up()
goto(0,-90)
down()
circle(90)
liste_angl=(0,30,45,60,90,120,135,150,180,210,225,240,270,300,315,330)
liste_str=("0 2π","π/6","π/4","π/3","π/2","2π/3","3π/4","5π/6","π -π","7π/6","5π/4","4π/3","3π/2","5π/3","7π/4","11π/6")
x=0
width(1)
color("grey")
down()
while x<=15:
goto(0,0)
setheading(liste_angl[x])
forward(90)
x=x+1
y=0
x=0
color("black")
up()
while x<=4:
y=-2
goto(0,0)
setheading(liste_angl[x])
forward(90+y)
write((liste_str[x]))
x=x+1
while 4<x<8:
y=17
goto(0,0)
setheading(liste_angl[x]+12)
forward(90+y)
write((liste_str[x]))
x=x+1
while 8<=x<=12:
y=23
goto(0,0)
setheading(liste_angl[x])
if x==8:
y=y+13
forward(90+y)
write((liste_str[x]))
x=x+1
while 12<x<=15:
y=14
goto(0,0)
setheading(liste_angl[x])
forward(90+y)
write((liste_str[x]))
x=x+1
up()
goto(0,0)
down()
write("0")
up()
goto(22,42)
down()
write("x")
up()
goto(22,-42)
down()
write("-x")
up()
goto(-42,42)
down()
write("x-π")
up()
goto(-42,-42)
down()
write("π-x")
"""
2d matrix for XY graph analysis
matrix_xy_stats() - function to analize a 2d matix to output information,
such as angle between <0,0> as theta, representing as x+yi, etc.
will use degriess as it will be easier.
valid inputs:
[[X,Y]] OR [[X],[Y]]
"""
from math import *
#from cmath import *
if 'complex' in globals():
__not_numworks = True
else:
__not_numworks = False
def matrix_xy_stats(matrix):
if len(matrix[0]) == 2:
x = matrix[0][0]
y = matrix[0][1]
else:
x = matrix[0][0]
y = matrix[1][0]
print("X:")
print("{0}".format(x))
print("Y:")
print("{0}".format(y))
print("theta degriess:")
theta = (atan2(y, x) * 180) / pi # degriees is disired
print(theta) # pre processed
while theta < 0:
theta += 360
while theta >= 360:
theta -= 360
print(theta) # after filters
print("magnitude:")
print("abs(abs({0}))".format(sqrt((x)**2+(y)**2)))
print("sqrt({0})".format((x)**2+(y)**2))
print("the imaginary i formula is:")
print("({0})+({1})*1j".format(x,y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment