Skip to content

Instantly share code, notes, and snippets.

@willmurphyscode
willmurphyscode / python-cosine-fixedpoint.py
Created September 13, 2017 11:09
Calculate the fixed point of cosine in Python
import math
tolerance = 0.00000000000000000001
def tolerance_equals(a, b):
return ((a - b) * (a - b)) < tolerance
def recursive_cosine_fixedpoint(a):
if tolerance_equals(a, math.cos(a)):
return a
@willmurphyscode
willmurphyscode / rust-cosine-fixedpoint.rs
Created September 13, 2017 11:10
Calculate the fixed point of cosine in Rust.
const TOLERANCE: f64 = 0.00000000000000000001;
fn tolerance_equals(a: f64, b: f64) -> bool {
((a - b) * (a - b)) < TOLERANCE
}
fn recursive_cosine_fixedpoint(a: f64) -> f64 {
if tolerance_equals(a, a.cos()) {
a
} else {
pub enum Token {
LeftParen,
RightParen,
Operator(Opcode),
Operand(isize)
}
pub enum Opcode {
Add, Subtract, Multiply, Divide,
}
named!(left_paren<&[u8], Token>,
do_parse!(tag!("(") >> (Token::LeftParen))
);
named!(right_paren<&[u8], Token>,
do_parse!(tag!(")") >> (Token::RightParen))
);
named!(addition_sign<&[u8], Token>,
do_parse!(tag!("+") >> (Token::Operator(Opcode::Add)))
named!(single_token<&[u8], Token>,
alt!(
left_paren |
right_paren |
addition_sign |
subtraction_sign |
multiplication_sign |
division_sign |
operand
)
pub fn parse(bytes: &[u8]) -> Result<Vec<Token>, TokenizationError> {
let parse_result = tokens(bytes).to_result();
match parse_result {
Ok(token_vec) => Ok(token_vec),
Err(_) => Err(TokenizationError {})
}
}
fn reduce_addition(stack: &mut Vec<Token>) -> Result<Token, RuntimeError> {
let operands = unwrap_operand_tokens(stack);
match operands {
Ok(operand_vec) => Ok(Token::Operand(
operand_vec
.iter()
.fold(0, |sum, value| sum + value))),
Err(_) => Err(RuntimeError{})
}
}
fn reduce_subtraction(stack: &mut Vec<Token>) -> Result<Token, RuntimeError> {
let operands = unwrap_operand_tokens(stack);
match operands {
Ok(mut operand_vec) =>{
let initial_positive_option = operand_vec.pop();
if let Some(initial_positive) = initial_positive_option {
Ok(Token::Operand(
operand_vec
.iter()
.fold(initial_positive, |sum, value| sum - value)))
pub fn reduce_or(stack: &mut Vec<Token>) -> Result<Token, RuntimeError> {
// would return Err if the vector were not entirely
// made of Token::Operand(Type::Bool), since we can't reduce with `or`
// other values
let bool_result = unwrap_boolean_tokens(stack);
if let Ok(bool_vec) = bool_result {
Ok(Token::Operand(Type::Bool(
bool_vec.iter().any(|b| *b) // and reducer has "all" here
)))
} else {
struct SomeCollection<'a> {
strings: Vec<&'a str>
}
impl<'a> SomeCollection<'a> {
pub fn new() -> Self {
SomeCollection { strings: Vec::new() }
}
pub fn insert(&mut self, s: &'a str) {