How to use chop with if in Mathematica? - if-statement

Suppose we have a set of 2 functions with multiple common arguments (x,y,z), let f_i(x,y,z) be one of those functions. When these arguments are evaluated by specific real numbers, Mathematica provides a solution which contains a real part and a very small irreal number (which I think is a calculation error), for the two functions.
I would like to create a new function with the same arguments that, when evaluated, chooses only the real part of the result of the function whose real result satisfies a certain criteria (e.g. be between -1 and 0).
This final function should allow me to plot the real part that matches the criteria in terms of any of its variables and to create other new functions.
I have tried the Chop and If functions in multiple orders without any success. My problem is that the chop function operates directly on the unevaluated functions and thus, does not allow me to attain the mentioned objective.
f[x_, y_, z_] =If[-1 <= Chop[f_1[x, y, z]] <= 0,Chop[f_1[x, y, z]],Chop[f_2[x, y, z]]]
Thank you very much.

Related

How to construct an XlaOp?

There are a number of functions for creating XlaOps from native C++ values. I'm trying to figure out how to use each to construct a graph. I've gone through xla_builder.h and picked out some candidates, omitting overloads and convenience wrappers. The two most likely candidates seem to be
// Enqueues a "retrieve parameter value" instruction for a parameter that was
// passed to the computation.
XlaOp Parameter(XlaBuilder* builder, int64 parameter_number, const Shape& shape,
const string& name);
// Enqueues a constant with the value of the given literal onto the
// computation.
XlaOp ConstantLiteral(XlaBuilder* builder, const LiteralSlice& literal);
Am I right in thinking Parameter is for "symbols", while ConstantLiteral is for constant values? For example, in f(x) = x + 1, we'd encode 1 as a ConstantLiteral, and then for x we could either
write f(x) as a C++ function, and at application site use another ConstantLiteral for our value of x, or
encode x using Parameter and build an XlaComputation from the corresponding XlaBuilder. That said, I'm not clear on how to actually call the XlaComputation with a Literal, other than with LocalClient which doesn't work with to multiple XlaComputations afaict.
What's the difference between these two approaches? Is one better than the other? I notice the former doesn't appear possible for higher-order functions: those which accept XlaComputations.
Next there's
Infeed, which I'd guess is a streaming version of Parameter.
Recv which looks like a way to pass data between computations, but doesn't actually create a completely new XlaOp itself.
ReplicaId, Iota, and XlaOp CreateToken(XlaBuilder* builder); appear largely irrelevant for this discussion.
Have I got this right? Are there any other important functions I've missed?

Why would I ever want to use Maybe instead of a List?

Seeing as the Maybe type is isomorphic to the set of null and singleton lists, why would anyone ever want to use the Maybe type when I could just use lists to accomodate absence?
Because if you match a list against the patterns [] and [x] that's not an exhaustive match and you'll get a warning about that, forcing you to either add another case that'll never get called or to ignore the warning.
Matching a Maybe against Nothing and Just x however is exhaustive. So you'll only get a warning if you fail to match one of those cases.
If you choose your types such that they can only represent values that you may actually produce, you can rely on non-exhaustiveness warnings to tell you about bugs in your code where you forget to check for a given a case. If you choose more "permissive" types, you'll always have to think about whether a warning represents an actual bug or just an impossible case.
You should strive to have accurate types. Maybe expresses that there is exactly one value or that there is none. Many imperative languages represent the "none" case by the value null.
If you chose a list instead of Maybe, all your functions would be faced with the possibility that they get a list with more than one member. Probably many of them would only be defined for one value, and would have to fail on a pattern match. By using Maybe, you avoid a class of runtime errors entirely.
Building on existing (and correct) answers, I'll mention a typeclass based answer.
Different types convey different intentions - returning a Maybe a represents a computation with the possiblity of failing while [a] could represent non-determinism (or, in simpler terms, multiple possible return values).
This plays into the fact that different types have different instances for typeclasses - and these instances cater to the underlying essence the type conveys. Take Alternative and its operator (<|>) which represents what it means to combine (or choose) between arguments given.
Maybe a Combining computations that can fail just means taking the first that is not Nothing
[a] Combining two computations that each had multiple return values just means concatenating together all possible values.
Then, depending on which types your functions use, (<|>) would behave differently. Of course, you could argue that you don't need (<|>) or anything like that, but then you are missing out on one of Haskell's main strengths: it's many high-level combinator libraries.
As a general rule, we like our types to be as snug fitting and intuitive as possible. That way, we are not fighting the standard libraries and our code is more readable.
Lisp, Scheme, Python, Ruby, JavaScript, etc., manage to get along with just one type each, which you could represent in Haskell with a big sum type. Every function handling a JavaScript (or whatever) value must be prepared to receive a number, a string, a function, a piece of the document object model, etc., and throw an exception if it gets something unexpected. People who program in typed languages like Haskell prefer to limit the number of unexpected things that can occur. They also like to express ideas using types, making types useful (and machine-checked) documentation. The closer the types come to representing the intended meaning, the more useful they are.
Because there are an infinite number of possible lists, and a finite number of possible values for the Maybe type. It perfectly represents one thing or the absence of something without any other possibility.
Several answers have mentioned exhaustiveness as a factor here. I think it is a factor, but not the biggest one, because there is a way to consistently treat lists as if they were Maybes, which the listToMaybe function illustrates:
listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe (a:_) = Just a
That's an exhaustive pattern match, which rules out any straightforward errors.
The factor I'd highlight as bigger is that by using the type that more precisely models the behavior of your code, you eliminate potential behaviors that would be possible if you used a more general alternative. Say for example you have some context in your code where you uses a type of the form a -> [b], though the only correct alternatives (given your program's specification) are empty or singleton lists. Try as hard as you may to enforce the convention that this context should obey that rule, it's still possible that you'll mess up and:
Somehow a function used in that context will produce a list of two or more items;
And somehow a function that uses the results produced in that context will observe whether the lists have two or more items, and behave incorrectly in that case.
Example: some code that expects there to be no more than one value will blindly print the contents of the list and thus print multiple items when only one was supposed to be.
But if you use Maybe, then there really must be either one value or none, and the compiler enforces this.
Even though isomorphic, e.g. QuickCheck will run slower because of the increase in search space.

Mathematical functions in functional programming

I have just started learning clojure.As it belongs to a category of functional programming,as a first step i am figuring out how it is different from imperative programming. So i have learnt from wikipedia and other sources some raw knowledge.So I am pretty confused with this line saying
There are functions in imperative programming and mathematical functions in functional programming .Here what do mathematical functions exactly mean?How is it different from functions.
Consider mathematically a function f(x)=X^2+X+1
In terms of object oreiented programming we write a function which accepts an argument x and returns the calculated value.I believe the same is the case with functional programming.Then what does it mean by
Treats computation as the evaluation of mathematical functions
and avoids changing-state and mutable data.
Thanks for help!!
By mathematical function it is meant a function that always returns the same value when called with the same inputs. The following, for example, is not a mathematical function:
a = 0
def f(x):
a += 1
return x + a
Because, of course, if you call it multiple times with the same x you will get back different values. This happens because f increments a, this is what is called side effect and is what should be avoided in functional programming.
This is a very broad question. You might want to read up on:
Programming Paradigms
Referential Transparency
In this case here, "mathematical functions" refers to the property of "not causing side-effects" e.g. printing to the display, changing variables or sending packets over the network. Functions in OO-languages do usually modify state (they change the values of the corresponding object instance), whereas in functional languages, they don't.
An example of a mathematical function (fullfills referential transparency, e.g. given the same input, it returns the same output):
def square(x):
return x * x
An example of two non-mathematical functions (__init__ and increment). These are still functions, but they are "changing" things e.g. the variable current_count):
class Counter:
def __init__(self):
self.current_count = 0
def increment():
self.current_count += 1

Using Brent algorithm to find the root of a function f with an initial guess, but without intervals [a,b] s.t. f(a)f(b)<0

I would like to know how to use Brent algorithm if no opposite signs can be provided.
For example, in the C++ library of Brent algorithm, the root-finding procedure that implements Brent’s method has to be used, following the header file, in the form of
double zero ( double a, double b, double t, func_base& f );
where a, b satisfies the condition of opposite signs: f(a).f(b) < 0
In my problem setting, I need to find the root(s) of a black-box function f. An initial guess is provided but no endpoints a,b, such that f(a) f(b)<0 are provided It seems that in Matlab there is a function fmin that only needs an initial guess. I would like to know how to do this using C++, in particular, using the implementation of Brent such as the one linked above?
Thanks for your ideas.
Without doing exhaustive search (and in the case of real valued function, you cannot, since the value of x is uncountable), there is no way to really guarantee finding the root if such exist.
One heuristic approach to address the problem is using gradient descent, in order to minimze (/maximize) the value of the function, until you find a local minimum (/maximum) or until you find a root.
The problem with this approach is you can get stuck in a local minimum (/maximum) before finding the root, and "think" there is no root, even if one does exist.
Under the assumptions that
f is a black-box, i.e. it can be evaluated but no information on its shape is known whatsoever.
You have to use a method that requires a priori knowledge of an interval [a,b] which brackets a root of f (assuming f is continuous).
I think your only option is to make a preliminary search for two valid points a and b.
This can be done in a number of ways. The most simple-minded could be to run a linear search (with some prescribed step) starting from your initial guess, which can be repeated with a finer step if it turns out unsuccessful. If f is not too "weird" a simple method should do.
Clearly, some basic clue on the properties of f is always necessary, for example that it actually has a root and that it is continuos, differentiable, etc.. All root finding methods (gradient descent, Newton-Raphson, bisection, etc.) assume some basic properties of the function.

Can I check whether a variable has deterministic value by C++ API

I noticed that Z3 can do allsmt from some paper. In my project, I have to search for deterministic variables in a SMT formula. By deterministic I mean the variable can only take one int value to make the formula satisfiable. Is there a c++/c API function which can do this task?
The best I can do so far is to call the solver.check() function many times for the negation of each variable I am interested in. Is there a faster way to do this by using the API?
Basically, I want to do allsmt and predicate abstraction/projection.
There is no specialized API for checking if all models of a given variable have to agree on the same value. You can implement more or less efficient algorithms on top of Z3 to solve this question.
Here is a possible algorithm:
Get a model M from Z3.
For the variables you are interested in assert: Not (And([(M.eval(x) == x) for x in Vars]))
Recheck satisfiability. If the new state is unsatisfiable, then the remaining variales in Vars must have the same value. Otherwise, remove variables from Vars that evaluate to a new value different from the old M.eval(x), and repeat (2) until Vars is either empty or the context is unsatisfiable.