proplem in program by python fractions - class

i have error in my code that write by python about fractions but I fase me proplem.
The error is that I don't know how to ask the object
Save the variable value of Objet and then call the aldea that do the mathematical operatio
plese help me to correct it

from fractions import*
# for testing vlaues
f12 = Fraction(1,2)
f44 = Fraction(4,4)
f128 = Fraction(12,8)
f32 = Fraction(3,2)
class Fraction:
def __init__ (self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
if self.denominator == 0:
raise ZeroDivisionError("sorry you are dividing by zero")
def sum(self, other):
numerator = (self.numerator * other.denominator) + (self.denominator +
other.numerator)
denominator = (self.denominator * other.denominator)
return Fraction(numerator/denominator)
def minus(self, other):
numerator = (self.numerator * other.denominator) - (self.denominator +
other.numerator)
denominator = (self.denominator * other.denominator)
return Fraction(numerator/denominator)
def times(self, other):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return Fraction(numerator/denominator)
def divid (self, other):
numerator = self.numerator * other.denominator
denominator = self.denominator * other.numerator
return Fraction(numerator/denominator)
def equals(self, other):
return self.numerator * other.denominator == self.denominator *
other.numerator
def test_suite(self,other):
if self == f12:
print(f"[{f12} + {f12} == {f12.sum(f12)} ] [4/4]")
elif self == f44 and other == f12:
print(f"[{f44} - {f12} == {f44.sum(f12)} ] [12/8]")
elif self == f12 and other == f44:
print(f"[{f12} + {f44} == {f12.minus(f44)} ] [4/8]")
elif self == f128 and other == f32:
print(f"[{f128} == {f32} == {f128.requal(f32)} ] [True]")
def main():
print("Wlecome to Fraction Caculator!")
numerator_1 = input("Fraction 1 Numerator: ")
denominator_1 = input("Fraction 1 denominator ")
f12 = Fraction(numerator_1, denominator_1)
numerator_2 = input("Fraction 2 Numerator: ")
denominator_2 = input("Fraction 2 denominator ")
f44 = Fraction(numerator_2, denominator_2)
#for texting parts
operation = print("Please enter the operation +, - , *, //, %, == ")
if operation == "+":
f12.sum(f44)
elif operation == "-":
f12.mins(f44)
elif operation == "*":
f12.times(f44)
elif operation == "//":
f12.divid(f44)
#for texting values
if __name__ == "_ _ main _ _ ":
main()

Related

Math operations with one line input. Any suggestions to improve this code?

'''I wrote this program so I could do the math operations like I do in a terminal. just add the numbers and the operators and hit enter. that will give me the result.
With this code same can be done. I am sharing this so I can get some feedback on how to make this more efficient, add more functionality to it, etc...'''
# Basic operator functions
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def dev(num1, num2):
return num1 / num2
operators = {'+': add, '-': sub, '*': mul, '/': dev}
def splitter(text):
"""Function to split an input string containing number and operators
in a list separating numbers and operators in given sequence"""
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', "."]
delimiter = ["+", "-", "*", "/"]
elist = []
num = ""
for char in text:
if char in numbers:
num += char
elif char in delimiter:
elist.append(float(num))
elist.append(char)
num = ""
elif char == " ":
continue
else:
print(f"Invalid input: {char}")
break
elist.append(float(num))
return elist
def calculator(splitter1):
result = splitter1
# print(result)
total = 0
while len(result) > 1:
if "/" in result:
o_index = result.index("/")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = dev(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "*" in result:
o_index = result.index("*")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = mul(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "+" in result:
o_index = result.index("+")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = add(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "-" in result:
o_index = result.index("-")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = sub(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
else:
continue
# print(result)
return total
repeat = "y"
while repeat == "y":
cal = input('calc: ')
calculation = calculator(splitter(cal))
print(calculation)
repeat = input("Would you like to continue to a new calculation? type 'y' to continue: ").lower()
else:
print("Thank you!")

How to format a number into thousands, millions and billions with dart/flutter?

How to get a number converted into something like this: 12K, 1.5M, 4.2B from a normal number like: 134900.
This is a minimalist function, of course you'll have to add validation code to verify if the number is valid before executing the function. Otherwise Enjoy ...
void main() {
double num = 1250;
var myNumber = k_m_b_generator(num);
print(myNumber);
}
String k_m_b_generator(num) {
if (num > 999 && num < 99999) {
return "${(num / 1000).toStringAsFixed(1)} K";
} else if (num > 99999 && num < 999999) {
return "${(num / 1000).toStringAsFixed(0)} K";
} else if (num > 999999 && num < 999999999) {
return "${(num / 1000000).toStringAsFixed(1)} M";
} else if (num > 999999999) {
return "${(num / 1000000000).toStringAsFixed(1)} B";
} else {
return num.toString();
}
}
You can use flutter's NumberFormat class with the compact function.
formatNumber(dynamic myNumber) {
// Convert number into a string if it was not a string previously
String stringNumber = myNumber.toString();
// Convert number into double to be formatted.
// Default to zero if unable to do so
double doubleNumber = double.tryParse(stringNumber) ?? 0;
// Set number format to use
NumberFormat numberFormat = new NumberFormat.compact();
return numberFormat.format(doubleNumber);
}
The answer is not entirely correct. If you test it, you will see what i meant. Base on the answer above, I created this solution:
String numberFormat(int n) {
String num = n.toString();
int len = num.length;
if (n >= 1000 && n < 1000000) {
return num.substring(0, len - 3) + '.' + num.substring(len - 3, 1 + (len - 3)) + 'k';
} else if (n >= 1000000 && n < 1000000000) {
return num.substring(0, len - 6) + '.' + num.substring(len - 6, 1 + (len - 6)) + 'm';
} else if (n > 1000000000) {
return num.substring(0, len - 9) + '.' + num.substring(len - 9, 1 + (len - 9)) + 'b';
} else {
return num.toString();
}
}

How can I write the code of Bessel function with 10 term in swift?

I hope you guys can check. when I use 5 as x it should be showing me -0.17749282815107623 but it returns -0.2792375. I couldn't where I have been doing the mistake.
var evenNumbers = [Int]()
for i in 2...10 {
if i % 2 == 0 {
evenNumbers.append(i)
}
}
func power(val: Float, power: Int)->Float{
var c:Float = 1
for i in 1...power {
c *= val
}
return c
}
func bessel(x: Float)->Float{
var j0:Float = 0
var counter = 1
var lastDetermVal:Float = 1
for eNumber in evenNumbers {
print(lastDetermVal)
if counter == 1 {
lastDetermVal *= power(val: Float(eNumber), power: 2)
j0 += (power(val: x, power: eNumber))/lastDetermVal
counter = -1
}else if counter == -1{
lastDetermVal *= power(val: Float(eNumber), power: 2)
j0 -= (power(val: x, power: eNumber))/lastDetermVal
counter = 1
}
}
return 1-j0
}
bessel(x: 5)
Function 1:
Your mistake seems to be that you didn't have enough even numbers.
var evenNumbers = [Int]()
for i in 2...10 {
if i % 2 == 0 {
evenNumbers.append(i)
}
}
After the above is run, evenNumbers will be populated with [2,4,6,8,10]. But to evaluate 10 terms, you need even numbers up to 18 or 20, depending on whether you count 1 as a "term". Therefore, you should loop up to 18 or 20:
var evenNumbers = [Int]()
for i in 2...18 { // I think the 1 at the beginning should count as a "term"
if i % 2 == 0 {
evenNumbers.append(i)
}
}
Alternatively, you can create this array like this:
let evenNumbers = (1..<10).map { $0 * 2 }
This means "for each number between 1 (inclusive) and 10 (exclusive), multiply each by 2".
Now your solution will give you an answer of -0.1776034.
Here's my (rather slow) solution:
func productOfFirstNEvenNumbers(_ n: Int) -> Float {
if n == 0 {
return 1
}
let firstNEvenNumbers = (1...n).map { Float($0) * 2.0 }
// ".reduce(1.0, *)" means "multiply everything"
return firstNEvenNumbers.reduce(1.0, *)
}
func nthTerm(_ n: Int, x: Float) -> Float {
let numerator = pow(x, Float(n) * 2)
// yes, this does recalculate the product of even numbers every time...
let product = productOfFirstNEvenNumbers(n)
let denominator = product * product
return numerator / (denominator) * pow(-1, Float(n))
}
func bessel10Terms(x: Float) -> Float {
// for each number n in the range 0..<10, get the nth term, add them together
(0..<10).map { nthTerm($0, x: x) }.reduce(0, +)
}
print(bessel10Terms(x: 5))
You code is a bit unreadable, however, I have written a simple solution so try to compare your intermediate results:
var terms: [Float] = []
let x: Float = 5
for index in 0 ..< 10 {
guard index > 0 else {
terms.append(1)
continue
}
// calculate only the multiplier for the previous term
// - (minus) to change the sign
// x * x to multiply nominator
// (Float(index * 2) * Float(index * 2) to multiply denominator
let termFactor = -(x * x) / (Float(index * 2) * Float(index * 2))
terms.append(terms[index - 1] * termFactor)
}
print(terms)
// sum the terms
let result = terms.reduce(0, +)
print(result)
One of the errors I see is the fact that you are actually calculating only 5 terms, not 10 (you iterate 1 to 10, but only even numbers).

How to check if x int start from y int via bits operations?

I need to check if x int start from other (y) int for example:
1) input: x = 1250; y = 12 output: True
2) input: x = 2500; y = 250 output: True
3) input: x = 22; y = 21 output: False
4) input: x = 150; y = 11 output: False
And I have no idea how to do it.
I have tried to use & operator but it is not enough:
let result = y & x
if result == y {
print("good")
}
How I can check it by using bit operations not using strings?
In the spirit of your comment that it doesn't matter which language this is in, here's a lazy C# implementation (that will port to C if you #include <stdbool.h>) that relies on the fact that integer division returns an int:
bool CheckPrefix(int x, int y)
{
while (y > x)
if ((y /= 10) == x)
return true;
return false;
}
In C#:
Console.WriteLine(CheckPrefix(12, 1250));
Console.WriteLine(CheckPrefix(250, 2500));
Console.WriteLine(CheckPrefix(21, 22));
Console.WriteLine(CheckPrefix(11, 150));
Outputs:
True
True
False
False
In C:
printf("%s", CheckPrefix(12, 1250) ? "true" : "false");
printf("%s", CheckPrefix(250, 2500) ? "true" : "false");
printf("%s", CheckPrefix(21, 22) ? "true" : "false");
printf("%s", CheckPrefix(11, 150) ? "true" : "false");
Outputs:
truetruefalsefalse
You can't do it via bits operations, like #ForceBru mentions in comment.
You can do it without using strings: just calculate digits count in both numbers, then "cut" bigger number and then compare if these numbers are equal:
func checkPrefix(_ prefix: Int, for number: Int) -> Bool {
let digitsDiff = digits(for: number) - digits(for: prefix)
if digitsDiff <= 0 {
return false
}
let digitsDiffPower = pow(10, Double(digitsDiff))
return number / Int(digitsDiffPower) == prefix
}
func digits(for number: Int) -> Int {
var num = number
var count = 0
while num != 0 {
count += 1
num = num / 10
}
return count
}
It works like you described:
print(checkPrefix(12, for: 1250)) // prints: true
print(checkPrefix(250, for: 2500)) // prints: true
print(checkPrefix(21, for: 22)) // prints: false
print(checkPrefix(11, for: 150)) // prints: false

Solve DAE with Pyomo and class

I'm trying to solve a car problem.
first, I have an original code of car problem:
# Ampl Car Example
#
# Shows how to convert a minimize final time optimal control problem
# to a format pyomo.dae can handle by removing the time scaling from
# the ContinuousSet.
#
# min tf
# dxdt = 0
# dvdt = a-R*v^2
# x(0)=0; x(tf)=L
# v(0)=0; v(tf)=0
# -3<=a<=1
from pyomo.environ import *
from pyomo.dae import *
m = ConcreteModel()
m.R = Param(initialize=0.001) # Friction factor
m.L = Param(initialize=100.0) # Final position
m.tau = ContinuousSet(initialize=[0.0, 0.80, 1.0]) # Unscaled time
m.time = Var(m.tau) # Scaled time
m.tf = Var()
m.x = Var(m.tau,bounds=(0,None))
m.v = Var(m.tau,bounds=(0,None))
m.a = Var(m.tau, bounds=(-3.0,1.0),initialize=0)
m.dtime = DerivativeVar(m.time)
m.dx = DerivativeVar(m.x)
m.dv = DerivativeVar(m.v)
m.obj = Objective(expr=m.tf)
def _ode1(m,i):
if i == 0 :
return Constraint.Skip
return m.dx[i] == m.tf * m.v[i]
m.ode1 = Constraint(m.tau, rule=_ode1)
def _ode2(m,i):
if i == 0 :
return Constraint.Skip
return m.dv[i] == m.tf*(m.a[i] - m.R*m.v[i]**2)
m.ode2 = Constraint(m.tau, rule=_ode2)
def _ode3(m,i):
if i == 0:
return Constraint.Skip
return m.dtime[i] == m.tf
m.ode3 = Constraint(m.tau, rule=_ode3)
def _init(m):
yield m.x[0] == 0
yield m.x[1] == m.L
yield m.v[0] == 0
yield m.v[1] == 0
yield m.time[0] == 0
m.initcon = ConstraintList(rule=_init)
discretizer = TransformationFactory('dae.collocation')
discretizer.apply_to(m,ncp=1, scheme='LAGRANGE-RADAU')
solver = SolverFactory('ipopt')
solver.solve(m, tee=True)
print("final time = %6.2f" %(value(m.tf)))
Now, I want to use class to express a car,then I could instantiate two cars.
So I write like this:
from pyomo.environ import *
from pyomo.dae import *
m = ConcreteModel()
class Car():
def __init__(self,friction):
self.friction = friction
self.R = Param(initialize = self.friction) # Friction factor
self.tau = ContinuousSet(bounds=(0, 1)) # Unscaled time
self.time = Var(self.tau) # Scaled time
self.tf = Var()
self.x = Var(self.tau, bounds=(0, None), initialize=0)
self.v = Var(self.tau, bounds=(0, None))
self.a = Var(self.tau, bounds=(-3.0, 1.0), initialize=0)
self.dtime = DerivativeVar(self.time)
self.dx = DerivativeVar(self.x)
self.dv = DerivativeVar(self.v)
def _ode1(m, i):
if i == 0:
return Constraint.Skip
return self.dx[i] == m.tf * self.v[i]
self.ode1 = Constraint(self.tau, rule=_ode1)
def _ode2(m, i):
if i == 0:
return Constraint.Skip
return self.dv[i] == m.tf * (self.a[i] - self.R * self.v[i] ** 2)
self.ode2 = Constraint(self.tau, rule=_ode2)
def _ode3(m, i):
if i == 0:
return Constraint.Skip
return self.dtime[i] == m.tf
self.ode3 = Constraint(self.tau, rule=_ode3)
m.car1 = Car(0.001)
m.obj = Objective(expr=m.car1.tf)
def _init(m):
yield m.car1.x[0] == 0
yield m.car1.x[1] == 100
yield m.car1.v[0] == 0
yield m.car1.v[1] == 0
yield m.car1.time[0] == 0
m.car1.initcon = ConstraintList(rule=_init)
discretizer = TransformationFactory('dae.finite_difference')
discretizer.apply_to(m, nfe=10, scheme='BACKWARD')
solver = SolverFactory('ipopt')
solver.solve(m, tee=True)
print("final time = %6.2f" % (value(m.car1.tf)))
However, I get this:
Traceback (most recent call last):
File "D:/pyo/pyomoceshi/ceshi3/car/classcar3.py", line 79, in <module>
solver.solve(m, tee=True)
File "D:\python\m\lib\site-packages\pyomo\opt\base\solvers.py", line 582, in solve
self._presolve(*args, **kwds)
File "D:\python\m\lib\site-packages\pyomo\opt\solver\shellcmd.py", line 196, in _presolve
OptSolver._presolve(self, *args, **kwds)
File "D:\python\m\lib\site-packages\pyomo\opt\base\solvers.py", line 661, in _presolve
**kwds)
File "D:\python\m\lib\site-packages\pyomo\opt\base\solvers.py", line 729, in _convert_problem
**kwds)
File "D:\python\m\lib\site-packages\pyomo\opt\base\convert.py", line 110, in convert_problem
problem_files, symbol_map = converter.apply(*tmp, **tmpkw)
File "D:\python\m\lib\site-packages\pyomo\solvers\plugins\converter\model.py", line 164, in apply
io_options=io_options)
File "D:\python\m\lib\site-packages\pyomo\core\base\block.py", line 1646, in write
io_options)
File "D:\python\m\lib\site-packages\pyomo\repn\plugins\ampl\ampl_.py", line 357, in __call__
include_all_variable_bounds=include_all_variable_bounds)
File "D:\python\m\lib\site-packages\pyomo\repn\plugins\ampl\ampl_.py", line 783, in _print_model_NL
list(self_varID_map[id(var)] for var in ampl_repn._linear_vars),
File "D:\python\m\lib\site-packages\pyomo\repn\plugins\ampl\ampl_.py", line 783, in <genexpr>
list(self_varID_map[id(var)] for var in ampl_repn._linear_vars),
KeyError: 68767416L
I want to know how to solve it or use other ways.
Below is a working version of your script. I changed things so that instead of a Car class there is a Car function that returns a Pyomo Block representing the car. By having a Car class you were essentially trying to create a subclass of Block and running into several subtle challenges that go along with that. You can see the blog post here for more information. The second change I made was in your declaration of the initial conditions, I changed the name of the ConstraintList from m.car1.initcon to m.car1_initcon. The difference is whether you want the ConstraintList to live on the car1 Block or the model. In your code, the 'dot' in the name meant you were trying to put it on the car1 Block but the constraints yielded in the rule were relative to the model. I changed the name to resolve this inconsistency.
from pyomo.environ import *
from pyomo.dae import *
m = ConcreteModel()
def Car(model, friction):
def construct_car_block(b):
b.R = Param(initialize = friction) # Friction factor
b.tau = ContinuousSet(bounds=(0, 1)) # Unscaled time
b.time = Var(b.tau) # Scaled time
b.tf = Var()
b.x = Var(b.tau, bounds=(0, None), initialize=0)
b.v = Var(b.tau, bounds=(0, None))
b.a = Var(b.tau, bounds=(-3.0, 1.0), initialize=0)
b.dtime = DerivativeVar(b.time)
b.dx = DerivativeVar(b.x)
b.dv = DerivativeVar(b.v)
def _ode1(b, i):
if i == 0:
return Constraint.Skip
return b.dx[i] == b.tf * b.v[i]
b.ode1 = Constraint(b.tau, rule=_ode1)
def _ode2(b, i):
if i == 0:
return Constraint.Skip
return b.dv[i] == b.tf * (b.a[i] - b.R * b.v[i] ** 2)
b.ode2 = Constraint(b.tau, rule=_ode2)
def _ode3(m, i):
if i == 0:
return Constraint.Skip
return b.dtime[i] == b.tf
b.ode3 = Constraint(b.tau, rule=_ode3)
return Block(rule=construct_car_block)
m.car1 = Car(m, friction=0.001)
m.obj = Objective(expr=m.car1.tf)
def _init(m):
yield m.car1.x[0] == 0
yield m.car1.x[1] == 100
yield m.car1.v[0] == 0
yield m.car1.v[1] == 0
yield m.car1.time[0] == 0
m.car1_initcon = ConstraintList(rule=_init)
discretizer = TransformationFactory('dae.finite_difference')
discretizer.apply_to(m, nfe=15, scheme='BACKWARD')
solver = SolverFactory('ipopt')
solver.solve(m, tee=True)
print("final time = %6.2f" % (value(m.car1.tf)))