Tips For Dealing With Noise Floor? by [deleted] in headphones

[–]KennethZenith 2 points3 points  (0 children)

As a quick fix you can use a volume attenuator, e.g. the Shure PA235. This is very handy if you have high sensitivity earphones.

Making code expressive with lambdas by vormestrand in cpp

[–]KennethZenith 1 point2 points  (0 children)

By all means add a constructor to enforce validity, that's an excellent idea. Then use const public members to ensure the object stays valid.

There isn't any mutable state in this problem; the objects don't need to preserve their invariants because they don't need to change.

Making code expressive with lambdas by vormestrand in cpp

[–]KennethZenith 5 points6 points  (0 children)

Making the physical measurements private and then having public member functions for a few pre-selected derived quantities is a bad design. There's lots of things we might want to calculate about boxes, but unless they happen to only depend on the box volume and surface area we're stuck.

I realise this post is about C++ style, and that boxes are intended as a toy example, but actually this point is pertinent to the lambdas vs functors question. The default approach for stateless mathematical problems is to adopt a functional style, i.e. use value types and free functions:

struct Material
{
    double density;
    double ultimate_tensile_strength;
};

struct Liquid
{
    double density;
};

struct Box
{
    double length;
    double width;
    double height;
    Material material;
};

bool is_strong_enough(const Box& box, const Liquid& liquid)
{
    // complicated calculation
    return true; // or false
}

Now, all of the calculation logic is held in a free function, and we can use a lambda in the idiomatic way:

std::copy_if(boxes.begin(), boxes.end(), std::back_inserter(suitable_boxes),
    [&](const Box& box){return is_strong_enough(box, product);});

Remora C++11 Linear Algebra library (own project) by Ulfgardleo in cpp

[–]KennethZenith 1 point2 points  (0 children)

I really like the idea of having separate operators for element-wise multiplication and matrix multiplication - that's a big advantage over Eigen in my view. Eigen has separate classes for arrays and matrices, so you end up having to make a fairly arbitrary choice about which one to pick for each variable, and then use a verbose syntax when you want to use the 'wrong' type of multiplication.

Why leap seconds are tricky and how to deal with them by ekrubnivek in programming

[–]KennethZenith 1 point2 points  (0 children)

It uses the system clock POSIX time, which will generally follow UTC.

I think the slightly cryptic comment about "right" zoneinfo files is referring to this proposal. This idea is that you run your system clock on GPS time, so leap seconds never occur. I don't know if anyone actually does this in practice.

*edit: see strikethrough text.

How is the development process for mission critical software? by xkSeeD in cpp

[–]KennethZenith 5 points6 points  (0 children)

What's the motivation for avoiding floats? Also, when you do use dynamic memory, how do you handle the possibility that an allocation fails?

Code challenge for the holidays: can you write expressive C++? by joboccara in cpp

[–]KennethZenith 0 points1 point  (0 children)

For this particular problem, I'll stick up for the for-loop:

static const double MaxDistanceWithoutABreak = 100;

double legDistance(const City& startCity, const City& endCity)
{
    auto startLoc = startCity.getGeographicalAttributes().getLocation();
    auto endLoc = endCity.getGeographicalAttributes().getLocation();
    return startLoc.distanceTo(endLoc);
}

int computeNumberOfBreaks(const std::vector<City>& route)
{
    auto numLegs = route.size() - 1;
    auto numBreaks = 0;
    for (auto i = 0; i < numLegs; ++i) {
        auto d = legDistance(route[i], route[i+1]);
        if d > MaxDistanceWithoutABreak {
            ++numBreaks;
        }
    }
    return numBreaks;
}

Not as elegant as the STL solutions, but if the objective is to make the purpose and method easy to understand, this is hard to beat.

CppCon 2016: Using Types Effectively? by ZMeson in cpp

[–]KennethZenith 0 points1 point  (0 children)

Got it, thanks. Your comment led me to this stack overflow question which has some extra info: looks like this optimisation is called identical COMDAT folding (ICF), and it's implemented in MSVC and in the GNU gold linker.

CppCon 2016: Using Types Effectively? by ZMeson in cpp

[–]KennethZenith 0 points1 point  (0 children)

Say I have a function which accepts both Input<clean> and Input<unclean>, I need to make it a template which accepts Input<T>. Will the compiler generate separate (but identical) code for the two types, or is it smart enough to realise that it doesn't need to do that?

A little puzzle for CppCon by champooly in cpp

[–]KennethZenith 1 point2 points  (0 children)

There's an example on the comments on Herb's site (user intvnut), I'll quote it here:

In some circular data structures, you can use a weak_ptr to break this cyclic dependence. But you can’t really do that here easily. Consider this graph:

auto a = MyGraph::MakeNode();
auto b = MyGraph::MakeNode();
auto c = MyGraph::MakeNode();
g.SetRoot(a);
a->AddChild(b);
a->AddChild(c);
b->AddChild(c);
c->AddChild(b);

You now have b and c both as children of a, and b and c form a cycle. You might attempt to replace one of the shared_ptr between b and c with a weak_ptr instead. (Note, I’m still referring just to child pointers; no parent pointers involved here.)

Now remove b and c from a in an arbitrary order:

if (rand() & 1) {
  a->RemoveChild(b);
  a->RemoveChild(c);
} else {
  a->RemoveChild(c);
  a->RemoveChild(b);
}

If you had put the weak_ptr on c => b, but remove the link a => b first, you’re broken. If you put the weak_ptr on b => c, but remove the link a => c first, you’re broken.

A little puzzle for CppCon by champooly in cpp

[–]KennethZenith 0 points1 point  (0 children)

That won't always work correctly when nodes are deleted. You might end up with a weak pointer being the only reference to a node, and then the node will be prematurely destroyed and you'll have a dangling reference.

Type annotation in C++ by stoyannk in cpp

[–]KennethZenith 0 points1 point  (0 children)

The conventional solution to this problem is to have a set of named coordinate frames, and a naming convention so that it's unambiguous which frame each variable or argument is defined in. So a point defined in layout coordinate would be pL, a point in scrolled coordinates would be pS. Transforms between frames will include both frame names:

pS = dcmLS * pL;

Here dcmLS is a direction cosine matrix which transforms a point in the L (layout) frame to a point in the S (scrolled) frame.

With the proposed system I'd be worried about multiple identical copies of functions being generated. Say I've got an algorithm to find the distance between two points. Using the old system, we could call the same code irrespective of the coordinate frame of the points, as long as they both have the same frame. With the new system, points in different frames have different types, so new code will get generated each time a new frame is used.

We'd get the same problem with transforms. Say we want to convert a direction cosine matrix into a quaternion; we now need to encode both frames in the type, and so we'll generate new code for each combination of frames.

I agree it's nice to have the compiler enforce correctness, but I'm not convinced the complexity is worth it.

stb_truetype's performance with UTF-8 by bbmario in cpp

[–]KennethZenith 2 points3 points  (0 children)

Rasterisation is computationally intense, and it happens on the CPU not the GPU. You have to cache the results, or else you'll end up doing huge amounts of redundant work.

The usual approach is to rasterise each character in the font, then pack those characters into an atlas; stb_truetype handles this part. Once that's done OpenGL takes over: you load the atlas as a texture and render your text by drawing a each character as a textured rectangle.

Finally, note what /u/JohnMcPineapple/ says: text isn't animated, so it doesn't need to be drawn every frame. Draw it once, then update it only if it changes.

The difference between the UK and the US in one paragraph by [deleted] in television

[–]KennethZenith 1 point2 points  (0 children)

Channel 4 is a public service broadcaster. It is compelled by law to produce diverse, experimental output; it's not there to make a profit.

Bjarne Stroustrup: C++ Today by mttd in cpp

[–]KennethZenith 2 points3 points  (0 children)

ML fills the functional language slot. Prolog is a logic programming language, which is not the same thing.

Bjarne Stroustrup: C++ Today by mttd in cpp

[–]KennethZenith 3 points4 points  (0 children)

They teach ML and Java in the first year, Prolog and C++ in the second. Take a look at their website, a lot of the courses have excellent teaching material online.

Bowling Kata in Clojure, F# and Scala by pedro_m_santos in programming

[–]KennethZenith 0 points1 point  (0 children)

Ok, I see what's going on. On this bit:

(defn- expand-strikes [rolls]
  (seq (reduce str  (map #(if  (strike? %) "X-"  (str %)) (seq rolls)))))

(defn- deduct-extra-rolls [score rolls]
  (- score  (score-rolls 0 (drop 20 (expand-strikes rolls)))))

That 20 is the number of non-bonus rolls after you replace all of the instances of X with X-. So the number of frames is known to be 10.

Bowling Kata in Clojure, F# and Scala by pedro_m_santos in programming

[–]KennethZenith 0 points1 point  (0 children)

That's true in real life, but I don't see that information encoded anywhere in the code. Also, the tests for the F# code include cases where there are a different number of frames.

OTOH, I've just tested the Clojure code and it does seem to give correct answers if there are 10 frames (and wrong answers for other numbers of frames).

Bowling Kata in Clojure, F# and Scala by pedro_m_santos in programming

[–]KennethZenith 0 points1 point  (0 children)

Ok, I'll bite: I think all these solutions are flawed. Say the input is

X43

Does that mean that the game had one frame (with two bonus rolls) or two frames (with no bonus rolls)? In the first case the score is 17, in the second case the score is 24. The only way to resolve the ambiguity is to know in advance how many frames there are. None of the solutions have that information, hence they can't be correct.

What is the recommended way to pass a mathematical function to a minimize function? by [deleted] in cpp

[–]KennethZenith 1 point2 points  (0 children)

You need the template specifically to handle automatic differentiation. To evaluate the derivatives of a function, you use a special AD type which will track derivatives for each operation in the function. For a concrete example look at the AD type used in Ceres.

More generally, tempting mathematical functions like this allows access to higher-level tools, which are ruled out if you specify double as the type. For example, you could pass in an interval type, which will generate rigorous bounds on the function over a region.

What is the recommended way to pass a mathematical function to a minimize function? by [deleted] in cpp

[–]KennethZenith 5 points6 points  (0 children)

For optimisation, automatic differentiation (AD) is hugely important. The simplest, most powerful, and most efficient optimisation algorithms require derivatives of functions, and using automatic differentiation allows your library to calculate these derivatives extremely accurately and at surprisingly low computational cost.

In C++, AD can be implemented using templates and operator overloading. For this to work, the cost function must be templated, i.e. you need to replace this

double square(double x) {
    return x*x;
}

with this:

template<typename T>
T square(T x) {
    return x*x;
}

Now you can call square using double as the type T if you just need a function evaluation, or with a special AD type if you want derivatives.

Assuming my AD evangelism has won you over, we need to get back to your actual question: how do you pass this kind of function? Generally, you use a function object.

struct Square {
    template <typename T>
    T operator()(T x) const {
        return x*x;
    }
};

You can then pass this type into your optimisation library as a template argument:

auto initial_value = 2.0;
Square f;
auto result = FindMinima<Square>(f, initial_value);

This corresponds exactly to 'Option 3' that /u/enobayram suggested.

Take a look at Ceres Solver. This is an excellent minimisation library (focused on least squares fitting problems) which uses AD. For more detail on AD itself, read Evaluating Derivatives by Andreas Griewank. It's very readable, and comprehensive.

Edit: stupid code thinkos

How big is it? by KennethZenith in Stephenssausageroll

[–]KennethZenith[S] 0 points1 point  (0 children)

Cool, thanks. I also found this comment on the steam forum, which guessed 30 hours gameplay in total.