Using max_by_key on a vector of floats [duplicate] - vector

This question already has answers here:
How do I get the minimum or maximum value of an iterator containing floating point numbers?
(4 answers)
Closed last year.
I want to use max_by_key to get the maximum value from a vector of f64s based on a certain key. This is a simple example, with a small vector and abs as the key:
let a: Vec<f64> = vec![-3.0, 0.2, 1.4];
*a.iter().max_by_key(|n| n.abs()).unwrap()
However, since f64 does not implement Ord, I get
error[E0277]: the trait bound `f64: std::cmp::Ord` is not satisfied
--> src/main.rs:3:15
|
3 | *a.iter().max_by_key(|n| n.abs()).unwrap();
| ^^^^^^^^^^ the trait `std::cmp::Ord` is not implemented for `f64`
Similarly, sort_by_key fails with the same error:
a.sort_by_key(|n| n.abs())
I know I can get around the partial ordering restriction to sort a vector of floats with sort_by
b.sort_by(|m, n| m.partial_cmp(n).unwrap_or(Less))
but that would have to be called on a vector b for which I've computed the key (in this case abs) for each element of a, and then I would have to go back and find the corresponding element of a, which seems complicated and slow. As the number of items in the list grows, I'd like to minimize passes through the data.
Are there any workarounds?

If you do not want to create a wrapper type you can use the ordered_float or ord_subset crate. For example
extern crate ordered_float;
extern crate ord_subset;
#[test]
fn test_example_() {
use ordered_float::OrderedFloat;
// OrderedFloat -> NaN is greater than all other values and equal to itself.
// NotNaN -> NotNaN::new panics if called with NaN.
let mut a: Vec<f64> = vec![-3.0, 0.2, 1.4];
let max = *a.iter().max_by_key(|n| OrderedFloat(n.abs())).unwrap();
assert_eq!(-3.0, max);
a.sort_by_key(|n| OrderedFloat(n.abs()));
assert_eq!(vec![0.2, 1.4, -3.0], a);
}
#[test]
fn test_example_ord_subset() {
use ord_subset::OrdSubsetIterExt;
let a: Vec<f64> = vec![-3.0, 0.2, 1.4];
// For f64, NaN is ignored.
let max = *a.iter().ord_subset_max_by_key(|n| n.abs()).unwrap();
assert_eq!(-3.0, max);
// ord_subset does not help with the sorting problem in the question
}

Related

Smallest distance in a list to the number 0 supplies amount of that number with map

I want to create a function absmin which gets a list of floating point numbers and returns the amount of that number which has the smallest distance to 0.
We should do it with the function map. My first idea was that the function abs mentioned the problem with amount, but know my question is, how it is possible to create the point with the smallest distance to 0 and that with the map function, can somebody help me?
absmin :: [Double] -> Int
absmin [] = []
absmin (x:xs) = abs (map (x:xs))
Okay, now i changed to:
absmin xs = map abs xs
But with the specification: absmin :: [Double] -> Double it didn't work, maybe i´m to stupid, but i try and try and it didn't work
If you have a list like [3.14, 2.98, -0.1] and need to find which number is closest to zero, you need to first map abs to that list, and then you need to find the min.
Now min has signature Ord a => a -> a -> a so it only considers two numbers at the same time. Fortunately we can use a fold to fold this function over our list.
Prelude> absmin = foldr1 min . map abs
Prelude> absmin [3.14, 2.98, -0.1]
0.1
The problem with this is that we don't know if the closest number to zero was 0.1 or -0.1.
So let's map each element to a tuple containing its absolute value and the original value. We can define a minBy function that lets us find the minimum of two values based on a function like fst.
After we've folded this function over the list of tuples, we just need to call snd on the result to get the original value.
Prelude> :{
Prelude| minBy f a b
Prelude| | f a <= f b = a
Prelude| | otherwise = b
Prelude| :}
Prelude> absmin' = snd . foldr1 (minBy fst) . map (\x -> (abs x, x))
Prelude> absmin' [3.14, 2.98, -0.1, 0.1]
-0.1
You can use the min() and abs() functions to find the smallest absolute value in a list of numbers, and then use map() to apply this value to each element in the list.

How do I check if the path from a node to another has a depth equal to a given one in a graph in OCaml?

First of all, I'm sorry for how I wrote my question.
Anyway, I'm trying to write a function in OCaml that, given a graph, a max depth, a starting node, and another node, returns the list of the nodes that make the path but only if the depth of it is equal to the given one. However, I can't implement the depth part.
This is what I did:
let m = [(1, 2, "A"); (2, 3, "A");
(3, 1, "A"); (2, 4, "B");
(4, 5, "B"); (4, 6, "C");
(6, 3, "C"); (5, 7, "D");
(6, 7, "D")]
let rec vicini n = function
[] -> []
| (x, y, _)::rest ->
if x = n then y :: vicini n rest
else if y = n then x :: vicini n rest
else vicini n rest
exception NotFound
let raggiungi m maxc start goal =
let rec from_node visited n =
if List.mem n visited then raise NotFound
else if n = goal then [n]
else n :: from_list (n :: visited) (vicini n m)
and from_list visited = function
[] -> raise NotFound
| n::rest ->
try from_node visited n
with NotFound -> from_list visited rest
in start :: from_list [] (vicini start m)
I know I have to add another parameter that increases with every recursion and then check if its the same as the given one, but I don't know where
I am not going to solve your homework, but I will try to teach you how to use recursion.
In programming, especially functional programming, we use recursion to express iteration. In an iterative procedure, there are things that change with each step and things that remain the same on each step. An iteration is well-founded if it has an end, i.e., at some point in time, the thing that changes reaches its foundation and stops. The thing that changes on each step, is usually called an induction variable as the tribute to the mathematical induction. In mathematical induction, we take a complex construct and deconstruct it step by step. For example, consider how we induct over a list to understand its length,
let rec length xs = match xs with
| [] -> 0
| _ :: xs -> 1 + length xs
Since the list is defined inductively, i.e., a list is either an empty list [] or a pair of an element x and a list, x :: list called a cons. So to discover how many elements in the list we follow its recursive definition, and deconstruct it step by step until we reach the foundation, which is, in our case, the empty list.
In the example above, our inductive variable was the list and we didn't introduce any variable that will represent the length itself. We used the program stack to store the length of the list, which resulted in an algorithm that consumes memory equivalent to the size of the list to compute its length. Doesn't sound very efficient, so we can try to devise another version that will use a variable passed to the function, which will track the length of the list, let's call it cnt,
let rec length cnt xs = match xs with
| [] -> cnt
| _ :: xs -> length (cnt+1) xs
Notice, how on each step we deconstruct the list and increment the cnt variable. Here, call to the length (cnt+1) xs is the same as you would see in an English-language explanation of an algorithm that will state something like, increment cnt by one, set xs to the tail xs and goto step 1. The only difference with the imperative implementation is that we use arguments of a function and change them on each call, instead of changing them in place.
As the final example, let's devise a function that checks that there's a letter in the first n letters in the word, which is represented as a list of characters. In this function, we have two parameters, both are inductive (note that a natural number is also an inductive type that is defined much like a list, i.e., a number is zero or the successor of a number). Our recursion is also well-founded, in fact, it even has two foundations, the 0 length and the empty list, whatever comes first. It also has a parameter that doesn't change.
let rec has_letter_in_prefix letter length input =
length > 0 && match input with
| [] -> false
| char :: input ->
char = letter || has_letter_in_prefix letter (length-1) input
I hope that this will help you in understanding how to encode iterations with recursion.

How to check equality of two FStar.Set's

How can you check whether two sets are equal in FStar? The following expression is of type Type0 not Tot Prims.bool so I'm not sure how to use it to determine if the sets are equal (for example in a conditional). Is there a different function that should be used instead of Set.equal?
Set.equal (Set.as_set [1; 2; 3]) Set.empty
The sets defined in FStar.Set are using functions as representation.
Therefore, a set s of integers for instance, is nothing else than a function mapping integers to booleans.
For instance, the set {1, 2} is represented as the following function:
// {1, 2}
fun x -> if x = 1 then true
else (
if x = 2 then true
else false
)
You can add/remove value (that is, crafting a new lambda), or asks for a value being a member (that is, applying the function).
However, when it comes to comparing two sets of type T, you're out of luck : for s1 and s2 two sets, s1 = s2 means that for any value x : T, s1 x = s2 x. When the set of T's inhabitants is inifinite, this is not computable.
Solution The function representation is not suitable for you. You should have a representation whose comparaison is computable. FStar.OrdSet.fst defines sets as lists: you should use that one instead.
Note that this OrdSet module requires a total order on the values held in the set. (If you want have set of non-ordered values, I implemented that a while ago, but it's a bit hacky...)

Multiplying fixed size fractions without using a larger container

I am given three unsigned numbers of size 128 bits: a, b, and c where a and b <= c I want to be able to calculate (a * b) / c with the highest possible precision.
If a, b, and c were 64 bit integers, I would first calculate a * b in a 128 bit number and then divide it by c to obtain an accurate result. However, I am dealing with 128 bit numbers and I don't have a native 256 bit type to perform the multiplication a * b.
Is there is a way to compute (a * b) / c with high precision while staying in the world of 128 bits?
My (failed) attempts:
Calculating a / (c / b). This looks somewhat unsymmetrical, and as expected I didn't get very accurate results.
Calculating: ((((a+b)/c)^2 - ((a-b)/c)^2)*c)/4 = ((a*b)/c^2) * c = a*b/c This also gave me pretty inaccurate results.
The question was originally tagged as rust, so I've assumed that in my answer, even though the tag has now been removed.
As others have said in the comments, you'll always have to step up a size or else you run the risk of an overflow on the multiplication, unless you have some guarantees about the bounds on the sizes of those numbers. There is no larger primitive type than u128 in Rust.
The usual solution is to switch to structures that support arbitrary-precision arithmetic, often referred to as "bignums" or "bigints". However, they are significantly less performant than using native integer types.
In Rust, you can use the num-bigint crate:
extern crate num_bigint;
use num_bigint::BigUint;
fn main() {
let a: u128 = 234234234234991231;
let b: u128 = 989087987;
let c: u128 = 123;
let big_a: BigUint = a.into();
let big_b: BigUint = b.into();
let big_c: BigUint = c.into();
let answer = big_a * big_b / big_c;
println!("answer: {}", answer);
// answer: 1883563148178650094572699
}

Problems with understanding recursion

I have problems with understanding recursion, I don't get the explanations in books and tutorials. The example below finds the greatest value in a list, here I get stuck at the second line, I simply don't understand what is happening after max([H|T], Max) when H > Max ->
I would really appreciate if I could get an explanation of all the steps in the code, for instance why it goes -> max(T, H); and -> Max.
max([H|T]) -> max(T, H).
max([H|T], Max) when H > Max -> max(T, H);
max([_|T], Max) -> max(T, Max);
max([], Max) -> Max.
Many thanks!
E.
I tried to explain step by step. Let's assume that you have a list: [2, 3, 1]
max([2, 3, 1]).
H=2 , T=[3, 1]
max([H|T]) -> max(T, H).
H=3, T=[1], Max=2
max([H|T], Max) when H > Max -> max(T, H);
Here when block says: if H is greater than Max then call max function again as max([1], 3).
Here we are again but with different values:
H=1, T=[], Max=3
max([H|T], Max) when H > Max -> max(T, H);
1 > 3 is false so when block fails and trying next max function definition which leads to step 5.
We know H is less than Max because step 4 failed so we are ignoring it.
T = [], Max=3
max([_|T], Max) -> max(T, Max);
We are matching last function definition which says max element found:
[] = [], Max = 3
max([], Max) -> Max.
Best way to understand recursion is by visualizing it. Let me give you a very simple example:
Suppose you want to know what is eligibility to become a prime minister of US, which is:
You have to be national citizen of US, for which here is the rule:
You are a natural born of US (or)
Your parents are national citizen of US
Now, first option straight forward makes you citizen of US, or same whole thing applies to your parents, which may again check for their parents ..and so on.
So there will be a straight forward answer, which is here 1st option. That is called Base Case. And in 2nd option you might apply same process of checking citizenship for your parents.
Here is a very simple pseudo code that can explain recursion:
isEligibleForPrimeMinister checkCitizenship(You, yourParents){
Base Case {returns true(That you are US citizen)}
checkCitizenship(yourParents, YourGrandParents)
}
Hope this helps.
This function could be rewritten like this:
max([H|T]) -> max(T, H).
max([], Max) -> Max;
max([H|T], Max) ->
NewMax = if H > Max -> H;
true -> Max
end,
%% NewMax = erlang:max(H, Max),
max(T, NewMax).
To understand it you must know how pattern matching works.
We take the head element of the list and consider it current maximum. We need to look at all the rest elements that are in the tail and check if any of them is greater.
If the rest of the list is empty, the current maximum is the result.
If the list is not empty take new head and determine the new maximum. Then go on with the rest of the list and new maximum. The thing that must be noticed here is that list passed to the next iteration of max/2 is always the tail of the previously passed value so we don't check values we already saw.
The last three lines in your code are all different clauses of the same function (max/2). This means that whenever the max function is called with two arguments passed, it will be pattern-matched against these three clauses.
This clause:
max([_|T], Max) -> max(T, Max);
will match whenever the list is non-empty and the head of the list (H) is less than or equal to Max. It will call max/2 passing T which is a list and Max which is a number. This new call will also be pattern-matched against the three clauses.
This clause:
max([], Max) -> Max.
will match whenever the list is empty and will return just Max which is a number.

Resources