text:
# Simplifying fraction over fraction expression

• October 17th 2010, 01:24 PM
Jodles
Simplifying fraction over fraction expression
Hi!

In physics I derived the following expression, and I have no idea where to start simplifying it:

$R_v = \frac{\frac{R_1 V_x}{E-V_x}R_2}{R_2 - \frac{R_1V_x}{E-V_x}}$

The lot in brackets is the same expression, so my hunch tells me this could be written much simpler? Or could it?

Jodles
• October 17th 2010, 01:30 PM
Also sprach Zarathustra
R_v={R_1V_xR_2}/{R_2{E-V_x}-R_1V_x}
• October 17th 2010, 01:30 PM
skeeter
Quote:

Originally Posted by Jodles
Hi!

In physics I derived the following expression, and I have no idea where to start simplifying it:

$R_v = \frac{\frac{R_1 V_x}{E-V_x}R_2}{R_2 - \frac{R_1V_x}{E-V_x}}$

The lot in brackets is the same expression, so my hunch tells me this could be written much simpler? Or could it?

Jodles

multiply numerator and denominator by $(E-V_x)$
• October 17th 2010, 02:27 PM
Jodles
Thank you very much! (Nod)


text:
Next: 5.4 Logarithms. Up: 5. Area Previous: 5.2 Further Assumptions About   Index

# 5.3 Monotonic Functions

5.27   Definition (Partition.) Let be real numbers with . A partition of the interval is a finite sequence of points

with . The intervals , are called the subintervals of the partition , and is the subinterval of for . The largest of the numbers is called the mesh of the partition , and is denoted by . The partition

is called the regular partition of into equal subintervals.

5.28   Example. Let

Then is a partition of into subintervals and .

The regular partition of into subintervals is .

If is the regular partition of into equal subintervals, then .

5.29   Exercise. Find a partition of into five subintervals, such that , or explain why no such partition exists.

5.30   Exercise. Find a partition of into five subintervals, such that , or explain why no such partition exists.

5.31   Definition (Monotonic function.) Let be an interval in , and let be a function. We say that is increasing on if
 (5.32)

and we say that is decreasing on if

We say that is strictly increasing on if

and we say that is strictly decreasing on if

We say that is monotonic on J if is either increasing on or decreasing on , and we say that is strictly monotonic on if is either strictly increasing or strictly decreasing on .

A constant function on is both increasing and decreasing on .

5.33   Notation () Let be a function from the interval to the non-negative numbers. We will write

i.e., is the set of points under the graph of over the interval .

Let be an increasing function from the interval to the non-negative numbers. Let be a partition of and let

Then

 (5.34)

To see this, observe that since is increasing

so

and also

By equation (5.34) and monotonicity of area, we have
 (5.35)

Now
 (5.36)

Now let be the mesh of (cf. definition 5.27) so that

Since for all , we have

for all , and hence
 (5.37)

Now

so by equations (5.37) and (5.36), we have

Now suppose that is any real number that satisfies

We will show that We have

It follows from (5.35) that

Thus
 (5.38)

for every partition of . Since we can find partitions with smaller than any preassigned number, it follows that
 (5.39)

(After we have discussed the notion of limit, we will come back and reconsider how (5.39) follows from (5.38). For the present, I will just say that the implication is intuitively clear.) We have now proved the following theorem:

5.40   Theorem. Let be an increasing function from the interval to , and let be a partition of . Let

 (5.41) (5.42)

Then
 (5.43)

and
 (5.44)

Also
 (5.45) (5.46)

If is any real number such that

then

The following picture illustrates the previous theorem.

5.47   Exercise. A version of theorem 5.40 for decreasing functions is also valid. To get this version you should replace the word increasing" by decreasing" and change lines (5.41), (5.42), (5.44), (5.45) and (5.46). Write down the proper versions of the altered lines. As usual, use to denote areas inside and to denote sets containing . Draw a picture corresponding to the above figure for a decreasing function.

5.48   Definition (Right triangle ) Let and be non-zero real numbers, and let . We define the triangle to be the set of points between the line segment and the -axis. By example 4.8, we know that the equation of the line through and is . Hence we have:

If and , then

If and , then

If and , then

If and , then

5.49   Remark. We know from Euclidean geometry that
 (5.50)

I would like to show that this relation follows from our assumptions about area. If , and are the reflections and rotation defined in definition 4.9, then we can show without difficulty that for and

so by invariance of area under symmetry,

when and are positive. It follows that if we prove formula (5.50) when and are positive, then the formula holds in all cases. For example if and are positive, and we know that (5.50) holds when and are positive, we get

and thus our formula holds when is negative and is positive.

5.51   Theorem. Let and be non-zero real numbers, and let be the set defined in definition 5.48. Then

Proof: By the previous remark, if is sufficient to prove the theorem for the case when and are positive. So suppose that and are positive.

Let . It appears from the figure, and is straightforward to show, that

By translation invariance of area,

We have

and

By the addition rule for area (assumption 5.14) we have

i.e.,

Thus our theorem will follow if we can show that the segment is a zero-area set. We will prove this as the next theorem.

5.52   Theorem. Let be a point in . Then

Proof: If or , then is a box with width equal to zero, or height equal to zero, so the theorem holds in this case. Hence we only need to consider the case where and are non-zero. Since any segment can be rotated or reflected to a segment where is in the first quadrant, we may further assume that and are both positive. Let be a positive integer, and for let

Then
 (5.53)

since

For each we have

Also the sets and are almost disjoint whenever and . (If and differ by more than 1, then and are disjoint, and if and differ by 1, then consists of a single point.) By additivity for almost-disjoint sets (assumption 5.25), it follows that

By (5.53) and monotonicity of area we have
 (5.54)

In order to conclude from this that We now make use of the Archimedean property of the real numbers, which says that for any real number there is a positive integer with . We know , since all areas are non-negative. Suppose (in order to get a contradiction) that is positive. Then by the Archimedean property, there is a positive integer such that . This implies that , and this contradicts (5.54). Hence is not positive, and we conclude that .

Archimedes' statement of the Archimedean property differs from our statement. He assumes that

Further, of unequal lines, unequal surfaces, and unequal solids, the greater exceeds the less by such a magnitude as, when added to itself, can be made to exceed any assigned magnitude among those which are comparable with [it and with] one another.[2, page 4]

5.55   Exercise. Let and be points in . Show that segment is a zero are set. (Use theorem 5.52. Do not reprove theorem 5.52).

5.56   Entertainment (Area of a triangle) Let , and be three points in , and let be the triangle with vertices , and . Let

Then the box is an almost-disjoint union of and three triangles which are translates of triangles of the form . Since you know how to find the area of a box and of a triangle , you can find the area of .

Using this remark show that for the triangles pictured below, , and .

Then choose another triangle with vertices and , where the coordinates of the points are related in a way different from the ways shown for and , and calculate the area of . You should find that

in all cases. Notice that if some coordinate is zero, the formula agrees with theorem 5.51.

Next: 5.4 Logarithms. Up: 5. Area Previous: 5.2 Further Assumptions About   Index
Ray Mayer 2007-09-07

format: plain


text:
# Copyright (c) 2015 Hong Xu <hong@topbug.net>

# This file is part of ParamComparison.

# ParamComparison is free software: you can redistribute it and/or modify it under the terms of the

# ParamComparison is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License along with
# ParamComparison. If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function

import abc
import six

"""
The base class for all readers, which define how to read and process data.
"""

@abc.abstractmethod
"""
:type params: dict
:param params: A dict which contains the values of parameters.

:return: The entry corresponding to the parameters.
:rtype: str
"""
raise NotImplementedError

"""
A class which relays the reading to a user function.
"""

def __init__(self, func, data):
"""
:type func: function
:param func: A user function which takes two parameters: data and params. The
function is defined by user and will be called in :func:read.
"""
self.func = func
self.data = data

params, and the second parameter of the data variable passed in in :func:__init__.
:return: What func returns.
.. seealso:: :func:Reader.read.


text:
A Neighborhood of Infinity

Sunday, November 12, 2006

Reverse Engineering Machines with the Yoneda Lemma

I've decided that the Yoneda lemma is the hardest trivial thing in mathematics, though I find it's made easier if I think about it in terms of reverse engineering machines. So, suppose you have some mysterious machine. You know it's a pure functional Haskell machine (of course) with no funny stuff (no overlapping or incoherent instances or anything like that [1]).

The machine works like this: for some fixed type A, whenever you give it a function of type A -> B it gives you back an object of type B. You can choose B to be whatever type you like, it always works. Is it possible to reproduce the machine exactly after testing it just a finite number of times? Sounds impossible at first, it seems the machine could do just about anything.

Think about how this machine could work. You can choose B freely, and whatever B you choose, it needs to come up with an object in B. There is no way to do this uniformly in Haskell without doing funny stuff. (I'm ruling undefined to be funny stuff too.) So how could this machine possibly generate a B? There's only one possible way, it must use the function of type A -> B to generate it. So that's how it works. It has an object a of type A and when you hand it an f it returns f a. You should also be able to convince yourself that there's no way it could vary the a depending on what f you give it. (Try writing a function that does!) Having narrowed the machine's principle down, it's now easy to figure out what a the machine is using. Just hand it id and it'll hand you back a. So in one trial you can deduce exactly what the machine does (at least up to functional equivalence).

We can specify this formally. The machine is of type: forall b . (a -> b) -> b. The process of extracting the a from the machine, by giving it the identity, can be described by this function:
> uncheck1 :: (forall b . (a -> b) -> b) -> a> uncheck1 t = t id

Given the output of the uncheck1 function, we can emulate the machine as follows:
> check1 :: a -> (forall b . (a -> b) -> b)> check1 a f = f a

You're probably wondering why the functions are called these names. See footnote [2] for that. I'll leave it to you to prove that check1 and uncheck1 are inverses to each other.

But now there's another machine to consider. This one takes as input a function A -> B and gives you back, not just one B but a whole list full of them. Maybe you're already guessing how it works. If it's generating a bunch of objects of type B then it must surely have a bunch of A's and it must be applying your function f to each one. In other words, the machine's behaviour must be something like this
> machine2 :: forall b . (a -> b) -> [b]> machine2 f = map f a where a = …to be determined…

So if this were the case, how would we determine what a was? How about using the same trick as before:
> uncheck2 :: (forall b . (a -> b) -> [b]) -> [a]> uncheck2 t = t id> check2 :: [a] -> (forall b . (a -> b) -> [b])> check2 a f = map f a

You should be able to prove that check2 and uncheck2 are mutual inverses.

> machine2' :: forall b . (a -> b) -> [b]> machine2' f = reverse $map f a where a = …to be determined… That has the correct type signature but it doesn't seem to have the same form as machine2. However, with a tiny bit of work we can show it's functionally equivalent to one that does. In fact we can just plug machine2' into uncheck2 and it will give us a list of A's that can be used in machine2. Instead of reverse we could use any function [a] -> [a] and we'd still get a sensible result out of check2. The reason is that if f is of type forall a.[a] -> [a] then f$ map g a equals map g $f a. (This is a Theorem for Free!.) So we can rewrite machine2' as > machine2'' :: forall b . (a -> b) -> [b]> machine2'' f = map f a where a = reverse$ …to be determined…

which looks just like our machine2. So however we munge up our list to make our machine unlike machine2 we can always 'commute' the munging to the right so it acts on the internal list of A's, converting into a machine like machine2.

One last example:

This time we hand our machine a A -> B and it gives us back another function, but this one is of the type C -> B, for some fixed C. It modifies the 'front end' of the input function so it can take a different argument. How could that possibly work? There's one obvious way: internally the machine is storing a function C -> A and when you hand it your function it returns the composition with the function it's storing.

Here's a potential design for this machine:
> machine3 :: forall b . (a -> b) -> (c -> b)> machine3 f = f . a where a x = …to be determined…

Maybe you think there's another type of machine that converts A -> B's to C -> B's. If you do, try writing it. But I think there isn't.

So now we can write the code to reverse engineer machine3:
> uncheck3 :: (forall b . (a -> b) -> (c -> b)) -> (c -> a)> uncheck3 t = t id> check3 :: (c -> a) -> (forall b . (a -> b) -> (c -> b))> check3 a f = f . a

uncheck3 pulls extracts the internally represented c -> a and check3 makes a functionally equivalent machine out of one.

So...I hope you're seeing the pattern. To make it easier, I'll define some functors:

> data I a = I a> instance Functor I where>    fmap f (I a) = I (f a)> instance Functor ((->) a) where>   fmap f = (.) f

Now all three example machines have the same form. For some functor f they map a function A -> B to an object of type f B and we deduce that internally they contain an f A. We can now write out versions of check and uncheck that work for all three machines:

> check :: Functor f => f a -> (forall b . (a -> b) -> f b)> check a f = fmap f a> uncheck :: (forall b . (a -> b) -> f b) -> f a> uncheck t = t id

The above examples follow when we consider the functors I, [] and ((->) c) (for various values of c) respectively.

Yoneda's lemma is essentially the statement that check and uncheck are mutual inverses. So if you understand my examples, then you're most of the way towards grokking the lemma.

At this point I should add some details. We're working in the category of Haskell types and functions Hask. Expanding out the category theoretical definition of a natural transformation, t between two functors f and g in Hask gives t . fmap f == fmap g . t. In this category, natural transformations correspond to polymorphic functions between functors with no funny stuff so this equality actually comes for free. (To be honest, I haven't seen a precise statement of this, but it's essentially what Theorems for Free! is about.) Yoneda's lemma actually says that for all functors f there is an isomorphism between the set of natural transformations of the type forall b . (a -> b) -> f b and the set of instances of f a. So now I can give proofs:

uncheck (check f)   = (check f) id        [defn of uncheck]   = fmap id f           [defn of check]   = id f                [property of fmap]   = f                   [defn of id]check (uncheck f) a   = check (f id) a        [use defn of uncheck]   = fmap a (f id)       [use defn of check]   = f (fmap a id)       [f natural]   = f (a . id)          [defn of fmap for ((>>) a)]   = f a                 [property of id]

I'll confirm that check f is natural, ie. that (check f) . (fmap g) = (fmap g) . (check f), although, as I mentioned above, this is automatically true for polymorphic functions without funny stuff.
check f (fmap g x)   = fmap (fmap g x) f   [defn of check]   = fmap (g . x) f      [defn of fmap for ((->) a)]   = (fmap g . fmap x) f [property of fmap]   = fmap g (fmap x f)   [defn of (.)]   = fmap g (check f x)    [defn of check]   = (fmap g . check f) x  [defn of (.)]

So that's it, Yoneda's lemma. It's trivial because the isomorphism is implemented by functions whose implementations are a couple of characters long. But it's hard because it took me ages to figure out what it was even about. I actually started with examples outside of Haskell. But Haskell has this weird property that polymorphic functions, with minor restrictions, are natural transformations. (I think this is the deepest mathematical fact about Haskell I've come across.) And as a result, Hask is an excellent category in which to learn about Yoneda's lemma.

I also recommend What's the Yoneda Lemma all about? by Tom Leinster. His presheaf example is the one at which these ideas started making sense to me - but that's because I've spent a lot of time playing with Čech cohomology on Riemann surfaces, so it might not work for everyone. This comment is also worth some thought. In fact, is the Yoneda lemma itself a Theorem for Free?

I haven't said anything about the deeper meaning of the Yoneda lemma. That might have something to do with the fact that I'm only just getting the hang of it myself...

And if you're still confused, let me quote the ubiquitous John Baez: "It took me ages to get the hang of the Yoneda lemm[a]". And nowadays he's one of the proprietors of the n-Category Café!

NB Everything I've said is modulo the equivalence of natural transformations and polymorphic unfunny functions. I may have got this wrong. If so, someone please correct me as I'm sure everything I say here will still hold after some minor edits :-)

[1] Consider the following compiled using GHC with -fallow-overlapping-instances -fglasgow-exts:

> class Test a where>     f :: a -> a> instance Test a where>     f = id> instance Test Int where>     f x = x+1

f is the identity for everything except for objects of type Int. This is an example of what I call "funny stuff".

[2] The accent on this letter 'č' is called a caron or háček. The book from which I learned about the Yoneda lemma used the caron to indicate the function I call check. I called it that because the TeX command to produce this symbol is \check. This is a multilayered pun, presumably by Knuth. It could just be that 'check' is an anglicised abbreviation for háček. But it's also a characterisically Czech accent so it's probably also an easier (for English speakers) spelling for 'Czech'. And I think it's also a pun on Čech. The caron is used on an H to represent Čech cohomology and so it's also called the 'Čech' accent. (I hope you can read those characters on a PC, I wrote this on a Mac.)

John Cowan said...

Feynman defined a trivial theorem as one that had been proved.

Thanks for making the Yoneda lemma start to make sense to me.

It seems that :check3 a f" should be "f . a" instead, no?

alpheccar said...

I have not yet totally understood the Yoneda Lemma but the best introduction I found so far is When is one thing equal to some other thing? by Barry Mazur

sigfpe said...

You're right. Maybe you can see the cause of my error. I originally wrote the code using fmap to effect the composition as defined later.

jkff said...

Thanks a lot, this is very cool. I am just now reading about the YL in 'Category theory for computing science' and I felt a strong desire to find an explanation in haskell. Would be cool if someone wrote a book on CT with explanations in Haskell, it seems to be often a lot more clear and understandable than standard mathematical notation.


text:
# Improved Definite Assignment Analysis

## Summary

Definite assignment §9.4 as specified has a few gaps which have caused users inconvenience. In particular, scenarios involving comparison to boolean constants, conditional-access, and null coalescing.

csharplang discussion of this proposal: https://github.com/dotnet/csharplang/discussions/4240

Probably a dozen or so user reports can be found via this or similar queries (i.e. search for "definite assignment" instead of "CS0165", or search in csharplang). https://github.com/dotnet/roslyn/issues?q=is%3Aclosed+is%3Aissue+label%3A%22Resolution-By+Design%22+cs0165

I have included related issues in the scenarios below to give a sense of the relative impact of each scenario.

## Scenarios

As a point of reference, let's start with a well-known "happy case" that does work in definite assignment and in nullable.

#nullable enable

C c = new C();
if (c != null && c.M(out object obj0))
{
obj0.ToString(); // ok
}

public class C
{
public bool M(out object obj)
{
obj = new object();
return true;
}
}

### Comparison to bool constant

if ((c != null && c.M(out object obj1)) == true)
{
obj1.ToString(); // undesired error
}

if ((c != null && c.M(out object obj2)) is true)
{
obj2.ToString(); // undesired error
}

### Comparison between a conditional access and a constant value

This scenario is probably the biggest one. We do support this in nullable but not in definite assignment.

if (c?.M(out object obj3) == true)
{
obj3.ToString(); // undesired error
}

### Conditional access coalesced to a bool constant

This scenario is very similar to the previous one. This is also supported in nullable but not in definite assignment.

if (c?.M(out object obj4) ?? false)
{
obj4.ToString(); // undesired error
}

### Conditional expressions where one arm is a bool constant

It's worth pointing out that we already have special behavior for when the condition expression is constant (i.e. true ? a : b). We just unconditionally visit the arm indicated by the constant condition and ignore the other arm.

Also note that we haven't handled this scenario in nullable.

if (c != null ? c.M(out object obj4) : false)
{
obj4.ToString(); // undesired error
}

## Specification

### ?. (null-conditional operator) expressions

We introduce a new section ?. (null-conditional operator) expressions. See the null-conditional operator specification (§11.7.7)and Precise rules for determining definite assignment §9.4.4 for context.

As in the definite assignment rules linked above, we refer to a given initially unassigned variable as v.

We introduce the concept of "directly contains". An expression E is said to "directly contain" a subexpression E1 if it is not subject to a user-defined conversion §10.5 whose parameter is not of a non-nullable value type, and one of the following conditions holds:

• E is E1. For example, a?.b() directly contains the expression a?.b().
• If E is a parenthesized expression (E2), and E2 directly contains E1.
• If E is a null-forgiving operator expression E2!, and E2 directly contains E1.
• If E is a cast expression (T)E2, and the cast does not subject E2 to a non-lifted user-defined conversion whose parameter is not of a non-nullable value type, and E2 directly contains E1.

For an expression E of the form primary_expression null_conditional_operations, let E0 be the expression obtained by textually removing the leading ? from each of the null_conditional_operations of E that have one, as in the linked specification above.

In subsequent sections we will refer to E0 as the non-conditional counterpart to the null-conditional expression. Note that some expressions in subsequent sections are subject to additional rules that only apply when one of the operands directly contains a null-conditional expression.

• The definite assignment state of v at any point within E is the same as the definite assignment state at the corresponding point within E0.
• The definite assignment state of v after E is the same as the definite assignment state of v after primary_expression.

#### Remarks

We use the concept of "directly contains" to allow us to skip over relatively simple "wrapper" expressions when analyzing conditional accesses that are compared to other values. For example, ((a?.b(out x))!) == true is expected to result in the same flow state as a?.b == true in general.

We also want to allow analysis to function in the presence of a number of possible conversions on a conditional access. Propagating out "state when not null" is not possible when the conversion is user-defined, though, since we can't count on user-defined conversions to honor the constraint that the output is non-null only if the input is non-null. The only exception to this is when the user-defined conversion's input is a non-nullable value type. For example:

public struct S1 { }
public struct S2 { public static implicit operator S2?(S1 s1) => null; }

This also includes lifted conversions like the following:

string x;

S1? s1 = null;
_ = s1?.M1(x = "a") ?? s1.Value.M2(x = "a");

x.ToString(); // ok

public struct S1
{
public S1 M1(object obj) => this;
public S2 M2(object obj) => new S2();
}
public struct S2
{
public static implicit operator S2(S1 s1) => null;
}

When we consider whether a variable is assigned at a given point within a null-conditional expression, we simply assume that any preceding null-conditional operations within the same null-conditional expression succeeded.

For example, given a conditional expression a?.b(out x)?.c(x), the non-conditional counterpart is a.b(out x).c(x). If we want to know the definite assignment state of x before ?.c(x), for example, then we perform a "hypothetical" analysis of a.b(out x) and use the resulting state as an input to ?.c(x).

### Boolean constant expressions

We introduce a new section "Boolean constant expressions":

For an expression expr where expr is a constant expression with a bool value:

• The definite assignment state of v after expr is determined by:
• If expr is a constant expression with value true, and the state of v before expr is "not definitely assigned", then the state of v after expr is "definitely assigned when false".
• If expr is a constant expression with value false, and the state of v before expr is "not definitely assigned", then the state of v after expr is "definitely assigned when true".

#### Remarks

We assume that if an expression has a constant value bool false, for example, it's impossible to reach any branch that requires the expression to return true. Therefore variables are assumed to be definitely assigned in such branches. This ends up combining nicely with the spec changes for expressions like ?? and ?: and enabling a lot of useful scenarios.

It's also worth noting that we never expect to be in a conditional state before visiting a constant expression. That's why we do not account for scenarios such as "expr is a constant expression with value true, and the state of v before expr is "definitely assigned when true".

### ?? (null-coalescing expressions) augment

We augment section §9.4.4.29 as follows:

For an expression expr of the form expr_first ?? expr_second:

• ...
• The definite assignment state of v after expr is determined by:
• ...
• If expr_first directly contains a null-conditional expression E, and v is definitely assigned after the non-conditional counterpart E0, then the definite assignment state of v after expr is the same as the definite assignment state of v after expr_second.

#### Remarks

The above rule formalizes that for an expression like a?.M(out x) ?? (x = false), either the a?.M(out x) was fully evaluated and produced a non-null value, in which case x was assigned, or the x = false was evaluated, in which case x was also assigned. Therefore x is always assigned after this expression.

This also handles the dict?.TryGetValue(key, out var value) ?? false scenario, by observing that v is definitely assigned after dict.TryGetValue(key, out var value), and v is "definitely assigned when true" after false, and concluding that v must be "definitely assigned when true".

The more general formulation also allows us to handle some more unusual scenarios, such as:

• if (x?.M(out y) ?? (b && z.M(out y))) y.ToString();
• if (x?.M(out y) ?? z?.M(out y) ?? false) y.ToString();

### ?: (conditional) expressions

We augment section §9.4.4.30 as follows:

For an expression expr of the form expr_cond ? expr_true : expr_false:

• ...
• The definite assignment state of v after expr is determined by:
• ...
• If the state of v after expr_true is "definitely assigned when true", and the state of v after expr_false is "definitely assigned when true", then the state of v after expr is "definitely assigned when true".
• If the state of v after expr_true is "definitely assigned when false", and the state of v after expr_false is "definitely assigned when false", then the state of v after expr is "definitely assigned when false".

#### Remarks

This makes it so when both arms of a conditional expression result in a conditional state, we join the corresponding conditional states and propagate it out instead of unsplitting the state and allowing the final state to be non-conditional. This enables scenarios like the following:

bool b = true;
object x = null;
int y;
if (b ? x != null && Set(out y) : x != null && Set(out y))
{
y.ToString();
}

bool Set(out int x) { x = 0; return true; }

This is an admittedly niche scenario, that compiles without error in the native compiler, but was broken in Roslyn in order to match the specification at the time. See internal issue.

### ==/!= (relational equality operator) expressions

We introduce a new section ==/!= (relational equality operator) expressions.

The general rules for expressions with embedded expressions §9.4.4.23 apply, except for the scenarios described below.

For an expression expr of the form expr_first == expr_second, where == is a[predefined comparison operator (§11.11) or a lifted operator (§11.4.8), the definite assignment state of v after expr is determined by:

• If expr_first directly contains a null-conditional expression E and expr_second is a constant expression with value null, and the state of v after the non-conditional counterpart E0 is "definitely assigned", then the state of v after expr is "definitely assigned when false".
• If expr_first directly contains a null-conditional expression E and expr_second is an expression of a non-nullable value type, or a constant expression with a non-null value, and the state of v after the non-conditional counterpart E0 is "definitely assigned", then the state of v after expr is "definitely assigned when true".
• If expr_first is of type boolean, and expr_second is a constant expression with value true, then the definite assignment state after expr is the same as the definite assignment state after expr_first.
• If expr_first is of type boolean, and expr_second is a constant expression with value false, then the definite assignment state after expr is the same as the definite assignment state of v after the logical negation expression !expr_first.

For an expression expr of the form expr_first != expr_second, where != is a predefined comparison operator (§11.11) or a lifted operator ((§11.4.8)), the definite assignment state of v after expr is determined by:

• If expr_first directly contains a null-conditional expression E and expr_second is a constant expression with value null, and the state of v after the non-conditional counterpart E0 is "definitely assigned", then the state of v after expr is "definitely assigned when true".
• If expr_first directly contains a null-conditional expression E and expr_second is an expression of a non-nullable value type, or a constant expression with a non-null value, and the state of v after the non-conditional counterpart E0 is "definitely assigned", then the state of v after expr is "definitely assigned when false".
• If expr_first is of type boolean, and expr_second is a constant expression with value true, then the definite assignment state after expr is the same as the definite assignment state of v after the logical negation expression !expr_first.
• If expr_first is of type boolean, and expr_second is a constant expression with value false, then the definite assignment state after expr is the same as the definite assignment state after expr_first.

All of the above rules in this section are commutative, meaning that if a rule applies when evaluated in the form expr_second op expr_first, it also applies in the form expr_first op expr_second.

#### Remarks

The general idea expressed by these rules is:

• if a conditional access is compared to null, then we know the operations definitely occurred if the result of the comparison is false
• if a conditional access is compared to a non-nullable value type or a non-null constant, then we know the operations definitely occurred if the result of the comparison is true.
• since we can't trust user-defined operators to provide reliable answers where initialization safety is concerned, the new rules only apply when a predefined ==/!= operator is in use.

We may eventually want to refine these rules to thread through conditional state which is present at the end of a member access or call. Such scenarios don't really happen in definite assignment, but they do happen in nullable in the presence of [NotNullWhen(true)] and similar attributes. This would require special handling for bool constants in addition to just handling for null/non-null constants.

Some consequences of these rules:

• if (a?.b(out var x) == true)) x() else x(); will error in the 'else' branch
• if (a?.b(out var x) == 42)) x() else x(); will error in the 'else' branch
• if (a?.b(out var x) == false)) x() else x(); will error in the 'else' branch
• if (a?.b(out var x) == null)) x() else x(); will error in the 'then' branch
• if (a?.b(out var x) != true)) x() else x(); will error in the 'then' branch
• if (a?.b(out var x) != 42)) x() else x(); will error in the 'then' branch
• if (a?.b(out var x) != false)) x() else x(); will error in the 'then' branch
• if (a?.b(out var x) != null)) x() else x(); will error in the 'else' branch

### is operator and is pattern expressions

We introduce a new section is operator and is pattern expressions.

For an expression expr of the form E is T, where T is any type or pattern

• The definite assignment state of v before E is the same as the definite assignment state of v before expr.
• The definite assignment state of v after expr is determined by:
• If E directly contains a null-conditional expression, and the state of v after the non-conditional counterpart E0 is "definitely assigned", and T is any type or a pattern that does not match a null input, then the state of v after expr is "definitely assigned when true".
• If E directly contains a null-conditional expression, and the state of v after the non-conditional counterpart E0 is "definitely assigned", and T is a pattern that matches a null input, then the state of v after expr is "definitely assigned when false".
• If E is of type boolean and T is a pattern which only matches a true input, then the definite assignment state of v after expr is the same as the definite assignment state of v after E.
• If E is of type boolean and T is a pattern which only matches a false input, then the definite assignment state of v after expr is the same as the definite assignment state of v after the logical negation expression !expr.
• Otherwise, if the definite assignment state of v after E is "definitely assigned", then the definite assignment state of v after expr is "definitely assigned".

#### Remarks

This section is meant to address similar scenarios as in the ==/!= section above. This specification does not address recursive patterns, e.g. (a?.b(out x), c?.d(out y)) is (object, object). Such support may come later if time permits.

This specification doesn't currently address scenarios involving pattern switch expressions and switch statements. For example:

_ = c?.M(out object obj4) switch
{
not null => obj4.ToString() // undesired error
};

It seems like support for this could come later if time permits.

There have been several categories of bugs filed for nullable which require we essentially increase the sophistication of pattern analysis. It is likely that any ruling we make which improves definite assignment would also be carried over to nullable.

## Drawbacks

It feels odd to have the analysis "reach down" and have special recognition of conditional accesses, when typically flow analysis state is supposed to propagate upward. We are concerned about how a solution like this could intersect painfully with possible future language features that do null checks.

## Alternatives

Two alternatives to this proposal:

1. Introduce "state when null" and "state when not null" to the language and compiler. This has been judged to be too much effort for the scenarios we are trying to solve, but that we could potentially implement the above proposal and then move to a "state when null/not null" model later on without breaking people.
2. Do nothing.

## Unresolved questions

There are impacts on switch expressions that should be specified: https://github.com/dotnet/csharplang/discussions/4240#discussioncomment-343395

## Design meetings

https://github.com/dotnet/csharplang/discussions/4243


text:
You've tried spherical_plot3d, it looks like.
Have you tried cylindrical_plot3d? If you give a more explicit example of what you need, this could help as well.


text:
# I need help understanding a few things regarding Least Squares Regression.

First of all, I imagine that I will get many downvotes on this since the questions are probably considered "stupid." However, please understand that I'm taking a class that is way above my head, and I'm not allowed to drop it. I'm asking these questions so that I know exactly what I need to learn without wasting time.

I'm taking a class in Big Data/Data Mining and I've been given an assignment to "do" least squares regression on a data set in Matlab. The problem is that I have never learned linear algebra before. I'm spending all my spare time catching up, but I feel like I will not make the deadline unless I focus only exactly on what the assignment requires.

I took notes during the classes, but I didn't know linear algebra back then so I couldn't understand what exactly I was writing. After spending weeks learning about vectors, matrices and subspaces, I understand some of it, but it's not enough.

Therefore, I ask you to help me understand the following:

1. If $x = [x(1), x(2), ... ,x(d)]$, then $\bar{x} = [1, x(1), x(2), ..., x(d)]$
(these are a column vectors, but I don't know the latex code).

However, I watched a Khan Academy video on linear regression where $\bar{x}$ was described as the mean value of $x$. From what I know, 'mean value' refers to a single (scalar) value and not a vector, so that has me confused. So, what does $\bar{x}$ actually mean?

2. The dependent value (I know the difference between independent and dependent values) is defined as $y(x) = w0 + w1x(1)+w2x(2)+...+ wdx(d)$

What on earth does $w$ mean? It's defined as a column vector ranging from $w0$ to $wd$.

3. What does $w*$ mean?

4. After doing the least squares regression, I'm asked to print the value of $w$ generated by the regression. Is this also a column vector or something completely different?

5. What am I actually trying to figure out with linear regression? A formula? A value? Nothing has been said about it in the class based on the notes I've taken, and I can't find any explanation in any book either. The closest I've gotten is that the objective is to "minimize the residuals." I understand what 'residual' means, but what is the output exactly?

I mean, I have training data. I use the regression formula on that data set. What am I left with that I can use on the test data?

6. Do I need to know anything about Eigen-values or anything involving "Eigen" in order to solve this problem?

Any help is greatly appreciated. Thank you.

• 3. (w*) is probably the transpose of the vector (w) but it depends on how it's defined in your class as (*) is used for many things. 5. The goal of linear regression to find the equation of a line which 'matches' your data the best. With this line you can predict values of (w) which you don't have data for. Oct 10, 2017 at 9:22
• The transpose of the matrix is defined as $x^T$. Also, in the notes I've taken, there's the equation $x^Ty = x^Txw^*$. Edit: I'm not sure but I think it's actually $w^*$ and not $w*$ Oct 10, 2017 at 9:27
• @TonyS.F. I'm answering a second time on your comment. Isn't the goal to predict the $y$ value of $x$? I mean, if $x$ is the independent, and $y$ is the dependent. Where does $w$ come in exactly? edit: In my previous comment, I mean that the transpose of the vector is defined as $x^T$, not the matrix. Oct 10, 2017 at 9:31
• Yes you are correct, you want to predict the values of the dependent variable, my mistake. You are also correct that usually xbar is not a vector, but a scalar quantity representing the arithmetic average. It seems, though, that your text/class also uses xbar to denote an 'augemented vector' i.e. they put another entry with a '1' in it. Oct 10, 2017 at 9:37
• Thanks! That's one mystery sort of solved. Although, I just googled 'augmented vector' and it seems like they put the '1' at the end/bottom and not at the top/beginning. Is that relevant? Oct 10, 2017 at 9:45

You are given a bunch of vectors $x_i \in \mathbb R^d$ and corresponding scalars $y_i \in \mathbb R$. Your goal is to find a vector $w \in \mathbb R^{d+1}$ such that $\bar x_i^T w \approx y_i$ for all $i$. We select $w$ to be the vector that minimizes the objective function $$E(w) = \sum_i (\bar x_i^T w - y_i)^2.$$ But minimizing $E(w)$ is something that we learned how to do in multivariable calculus. Just set the gradient of $E$ equal to $0$, and solve for $w$.
• @Lobs001 No, I don't mean that you should set $E(w)$ equal to $0$. In precalculus, you have learned to find the minimum point (vertex) on a parabola by the technique of completing the square. So, minimizing a quadratic function of one variable is something that you know how to do from precalculus. In calculus you will learn a different method for minimizing functions: you set the derivative equal to $0$. So, how do we minimize $E(w)$? Well, $E(w)$ is a quadratic function of several variables $w_0, w_1,\ldots, w_d$. You can either "complete the square" or "set the derivative to $0$". Oct 11, 2017 at 3:35
• It is difficult to understand the details without knowing some multivariable calculus and linear algebra. Multivariable calculus and linear algebra are prerequisites for machine learning. Here is an overview: it is possible to rewrite $E(w)$ using matrix notation as $E(w) = \| X w - y \|^2$. Here $X$ is the matrix whose $i$th row is $\bar x_i^T$, and $y$ is the column vector whose $i$th component is $y_i$. From multivariable calculus, the gradient of $E$ is $\nabla E(w) = 2 X^T (Xw - y)$. Set the gradient of $E$ equal to $0$ and we get $X^T Xw = X^T y$. Now solve for $w$. Oct 11, 2017 at 3:41
• The equations $X^T X w = X^T y$ are called the "normal equations". You can solve a least squares problem by writing down and then solving the normal equations. Oct 11, 2017 at 3:42


text:
# 2.4. Using RegEx with spaCy#

## 2.4.1. What is Regular Expressions (RegEx)?#

Regular Expressions, or RegEx for short, is a way of achieving complex string matching based on simple or complex patterns. It can be used to perform finding and retrieving patterns or replacing matching patterns in a string with some other pattern. It was invnted by an Stephen Cole Kleene in the 1950s and is still widely used today for numerous tasks, but particularly string matching in texts. RegEx are fully integrated with most search engines and can allow for more robust searching. Nearly all data scientists, especially those who work with texts, use RegEx at some stage in their workflow, from data searching, to cleaning data, to implementing machine learning models. It is an essential tool for any text-based researcher. For these reasons, it merits a few chapters in this textbook.

In spaCy it can be leveraged in a few different pipes (depending on the task at hand as we shall see), to identify things such as entities or pattern matching.

## 2.4.2. The Strengths of RegEx#

There are several strengths to RegEx.

1. Due to its complex syntax, it can allow for programmers to write robust rules in short spaces.

2. It can allow the researcher to find all types of variance in strings

3. It can perform remarkably quickly when compared to other methods.

4. It is universally supported

## 2.4.3. The Weaknesses of RegEx#

Despite these strengths, there are a few weaknesses to RegEx.

1. Its syntax is quite difficult for beginners. (I still find myself looking up how to do certain things).

2. It order to work well, it requires a domain-expert to work alongside the programmer to think of all ways a pattern may vary in texts.

## 2.4.4. How to Use RegEx in Python#

Python comes prepackaged with a RegEx library. We can import it like so:

import re

Now that we have it imported, we can begin to write out some RegEx rules. Let’s say we want to find an occurrence of a date in a text. As noted in an earlier notebook, there are a finite number of ways this can be represented. Let’s try to grab all instances of a day followed by a month first.

pattern = r"((\d){1,2} (January|February|March|April|May|June|July|August|September|October|November|December))"

text = "This is a date 2 February. Another date would be 14 August."
matches = re.findall(pattern, text)
print (matches)

[('2 February', '2', 'February'), ('14 August', '4', 'August')]

In this bit of code, we see a real-life RegEx formula at work. While this looks quite complex, its syntax is fairly straight forward. Let’s break it down. The first ( tells RegEx that I’m looking for something within the ending ). In other words, I’m looking for a pattern that’s going to match the whole pattern, not just components.

Next, we state (\d){1,2}. This means that we are looking for any digit (0-9) that occurs either once or twice ({1,2}).

Next, we have a space to indicate the space in the string that we would expect with a date.

Next, we have (January|February|March|April|May|June|July|August|September|October|November|December) – this indicates another component of the pattern (because it is parentheses). The | indicates the same concept as “or” in English, so either January, or February, or March, etc.

When we bring it together, this pattern will match anything that functions as a set of one or two numbers followed by a month. What happens when we try and do this with a date that is formed the opposite way?

text = "This is a date February 2. Another date would be 14 August."
matches = re.findall(pattern, text)
print (matches)

[('14 August', '4', 'August')]

It fails. But this is no fault of RegEx. Our pattern cannot accommodate that variation. Nevertheless, we can account for it by adding it as a possible variation. Possible variations are accounted for with a *

pattern = r"(((\d){1,2}( (January|February|March|April|May|June|July|August|September|October|November|December)))|(((January|February|March|April|May|June|July|August|September|October|November|December) )(\d){1,2}))"

text = "This is a date February 2. Another date would be 14 August."
matches = re.findall(pattern, text)
print (matches)

[('February 2', '', '', '', '', 'February 2', 'February ', 'February', '2'), ('14 August', '14 August', '4', ' August', 'August', '', '', '', '')]

There are more concise ways to write the same RegEx formula. I have opted here to be more verbose to make it a bit easier to read. You can see that we’ve allowed for two main options for our pattern matcher.

Notice, however, that we have a lot of superfluous information for each match. These are the components of each match. There are several ways we can remove them. One way is to use the command finditer, rather than findall in RegEx.

text = "This is a date February 2. Another date would be 14 August."
iter_matches = re.finditer(pattern, text)
print (iter_matches)

<callable_iterator object at 0x00000217A415BC10>

This is an iterator object, we can loop over it, however, and get our results.

text = "This is a date February 2. Another date would be 14 August."
iter_matches = re.finditer(pattern, text)
print (iter_matches)
for hit in iter_matches:
print (hit)

<callable_iterator object at 0x00000217A4256670>
<re.Match object; span=(15, 25), match='February 2'>
<re.Match object; span=(49, 58), match='14 August'>

Within each of these is some very salient information, such as the start and end location (inside the span) and the text itself (match). We can use the start and end location to grab the text within the string.

text = "This is a date February 2. Another date would be 14 August."
iter_matches = re.finditer(pattern, text)
for hit in iter_matches:
start = hit.start()
end = hit.end()
print (text[start:end])

February 2
14 August

## 2.4.5. How to Use RegEx in spaCy#

Things like dates, times, IP Addresses, etc. that have either consistent or fairly consistent structures are excellent candidates for RegEx. Fortunately, spaCy has easy ways to implement RegEx in three pipes: Matcher, PhraseMatcher, and EntityRuler. One of the major drawbacks to the Matcher and PhraseMatcher, is that they do not align the matches as doc.ents. Because this textbook is about NER and our goal is to store the entities in the doc.ents, we will focus on using RegEx with the EntityRuler. In the next notebook, we will examine other methods.

In the previous notebook, we saw how the code below allowed for us to capture the phone number in the string. I have modified it a bit here for reasons that will become a bit more clear below.

#Import the requisite library
import spacy

#Sample text
text = "This is a sample number 555-5555."

#Build upon the spaCy Small Model
nlp = spacy.blank("en")

#Create the Ruler and Add it

#List of Entities and Patterns (source: https://spacy.io/usage/rule-based-matching)
patterns = [
{"label": "PHONE_NUMBER", "pattern": [{"SHAPE": "ddd"},
{"ORTH": "-", "OP": "?"}, {"SHAPE": "dddd"}]}
]

#create the doc
doc = nlp(text)

#extract entities
for ent in doc.ents:
print (ent.text, ent.label_)

INFO:tensorflow:Enabling eager execution
INFO:tensorflow:Enabling v2 tensorshape
INFO:tensorflow:Enabling resource variables
INFO:tensorflow:Enabling tensor equality
INFO:tensorflow:Enabling control flow v2
555-5555 PHONE_NUMBER

This method worked well for grabbing the phone number. But what if we wanted to use RegEx as opposed to linguistic features, such as shape? First, let’s write some RegEx to capturee 555-5555.

pattern = r"((\d){3}-(\d){4})"
text = "This is a sample number 555-5555."
matches = re.findall(pattern, text)
print (matches)

[('555-5555', '5', '5')]

Okay. So, now we know that we have a RegEx pattern that works. Let’s try and implement it in the spaCy EntityRuler. We can do that with the code below. When we execute the code below, we have no output.

#Import the requisite library
import spacy

#Sample text
text = "This is a sample number (555) 555-5555."

#Build upon the spaCy Small Model
nlp = spacy.blank("en")

#Create the Ruler and Add it

#List of Entities and Patterns (source: https://spacy.io/usage/rule-based-matching)
patterns = [
{
"label": "PHONE_NUMBER", "pattern": [{"TEXT": {"REGEX": "((\d){3}-(\d){4})"}}
]
}
]

#create the doc
doc = nlp(text)

#extract entities
for ent in doc.ents:
print (ent.text, ent.label_)

This is for one very important reason. SpaCy’s EntityRuler cannot use RegEx to pattern match across tokens. The dash in the phone number throws off the EntityRuler. So, what are we to do in this scenario? Well, we have a few different options that we will explore in the next notebook. But before we get to that, let’s try and use RegEx to capture the phone number with no hyphen.

#Import the requisite library
import spacy

#Sample text
text = "This is a sample number 5555555."
#Build upon the spaCy Small Model
nlp = spacy.blank("en")

#Create the Ruler and Add it

#List of Entities and Patterns (source: https://spacy.io/usage/rule-based-matching)
patterns = [
{
"label": "PHONE_NUMBER",
"pattern": [{"TEXT": {"REGEX": "((\d){5})"}}
]
}
]

5555555 PHONE_NUMBER


text:
# What is phase constant

1. ### justwild

53
I just started learning Simple Harmonic Motion and encountered a word Phase Constant $\phi$ .
Actually it appeared as
f(t)=rsin($\omega t+\phi$)
I am confused whether phase constant is actually the initial position of the particle(which execute SHM) and therefore the point on graph at time=0 or not!!!

2. Physics news on Phys.org
3. ### tiny-tim

26,055
welcome to pf!

hi justwild! welcome to pf!

you're right, the phase constant is the initial angle (or initial phase): the angle (or phase) at t = 0

4. ### justwild

53
what is the harm if we just take $\omega t$ as the argument.

1,609
You just shift the motion in phase slightly. All te same key features are there.

6. ### justwild

53
If $\phi$ is the initial angle then I think the sinusoidal graph will show different starting points(t=0) for different values of $\phi$ of the same amplitude and frequency of vibration. Is that so???

7. ### tiny-tim

26,055
you can eliminate the phase constant by changing the starting time …

if you replace t by t + φ/ω, then the phase constant is zero
not following you


text:
# Is it a Lynch-Bell number?

You will be given a positive, whole number (that will never contain a 0) as input. Your task is to check whether it is a Lynch-Bell number or not.

A number is a Lynch-Bell number if all of its digits are unique and the number is divisible by each of its digits.

In fact, there are actually only 548 Lynch-Bell numbers, so hard-coding is a possibility, but will almost certainly be longer.

126 is a Lynch-Bell number because all of its digits are unique, and 126 is divisible by 1, 2, and 6.

You can output any truthy and falsy value.

## Examples:

7 -> truthy
126 -> truthy
54 -> falsy
55 -> falsy
3915 -> truthy

This is OEIS A115569.

• Related. (Asks for all the numbers instead of posing a decision problem.) – Martin Ender Jul 4 '17 at 11:54
• Can I take input as a string? – TheLethalCoder Jul 4 '17 at 12:38
• @TheLethalCoder Of course you can, that's a silly question. – Okx Jul 4 '17 at 12:40
• @Okx Not all challenge posters are as flexible in their allowed inputs as you so always worth an ask. – TheLethalCoder Jul 4 '17 at 12:41

## Mathematica, 42 bytes

0!=##&@@d&&##&@@((d=IntegerDigits@#)∣#)&

I think 0!=##&@@d&&##&@@ is a new low in readability for Mathematica...

### Explanation

Some of the basic syntactic sugar used here:

• & has very low precedence and turns everything left of it into an unnamed function.
• && is just the And operator.
• # is the argument of the nearest enclosing unnamed function.
• ## is a sequence of all of the function's arguments.
• @ is prefix notation for function calls, i.e. f@x == f[x].
• @@ is Apply, which passes the elements of a list as individual arguments to a function, i.e. f@@{a,b,c} == f[a,b,c].

With that out of the way...

(d=IntegerDigits@#)

This should be fairly self-explanatory: this gives us a list of the input's decimal digits and stores the result in d.

(...∣#)

This tests the input for divisibility by each of its digits (because the divisibility operator is Listable). This gives us a list of Trues and Falses.

...&@@...

We apply the function on the left-hand side to the list of booleans, such that each boolean is a separate argument.

...&@@d

We apply another function to d, so that the individual digits are given as separate arguments. The function is 0!=##&, i.e. Unequal[0, d1, d2, ...]. It checks that all the digits are distinct (and that they are distinct from 0 but that's given by the challenge, and if it wasn't, it wouldn't be a divisor anyway). 0!=##& is really just a 1-byte saver on using Unequal itself, and it works because there's a 1-byte element (0) that we know is not present. So this first thing checks that the digits are unique. Let's call this result U

...&&##

Again, this is really just shorthand for And[U, ##]. With ## being a sequences, the individual booleans from the initial divisibility check are expanded into the And, so we get And[U, d1∣n, d2∣n, ...] which checks that both the digits are unique and each digit divides the input.

• ##&@@d&&##&@@? What does that even do? – Okx Jul 4 '17 at 12:03
• @Okx Added an explanation. – Martin Ender Jul 4 '17 at 12:12
• May be you can replace 0!= by 0< ? – sergiol Jul 4 '17 at 14:26
• @sergiol I'd have to sort the digits to do that. – Martin Ender Jul 4 '17 at 14:49
• New low in readability indeed, normally Mathematica looks like a bunch of syntax-sugar around a few function names I can understand, I was unaware you could make a program entirely out of the sugar :p (of course, your excellent explanation let's me see that its of course not all sugar, but still, very impressive!) – mbrig Jul 4 '17 at 19:13

# Python 3, 56 bytes

lambda n:any(int(n)%int(x)for x in n)or len(n)>len({*n})

Try it online!

Output False if it's IS a Lynch-Bell number, True otherwise.

• Is this inputting as a string? – CalculatorFeline Jul 5 '17 at 17:18
• This has two problems: 1) it doesn't give truthy/falsey answers as specified (it's just 4 bytes!); 2) it throws an exception on the input "10". Otherwise, very nice and concise! – CR Drost Jul 5 '17 at 17:33
• @CalculatorFeline Yes. – CR Drost Jul 5 '17 at 17:33
• @CRDrost 1) the ouput well defined so there is no problem (usually) 2) there will never be 0 in the input – Rod Jul 5 '17 at 17:45
• 1) I mean, there is a problem, which is that they asked for X and you did not give it. 2) Ah, you're totally right, I missed that completely. – CR Drost Jul 5 '17 at 17:55

# Brachylog, 10 bytes

≠g;?z%ᵐ=h0

Try it online!

### Explanation

≠             All digits are different
g;?z         Zip the input with each of its digits
%ᵐ       Map mod
=      All results are equal
h0    The first one is 0

# C#, 87 83 bytes

using System.Linq;s=>s.Distinct().Count()==s.Length&s.All(c=>int.Parse(s)%(c-48)<1)

I wrote this in notepad before testing in Visual Studio, where it worked fine, so just realised I'm now that level of nerd...

Full/Formatted Version:

using System;
using System.Linq;

class P
{
static void Main()
{
Func<string, bool> f = s => s.Distinct().Count() == s.Length
& s.All(c => int.Parse(s) % (c - 48) < 1);

Console.WriteLine(f("7"));
Console.WriteLine(f("126"));
Console.WriteLine(f("54"));
Console.WriteLine(f("55"));
Console.WriteLine(f("3915"));

}
}

## JavaScript (ES6), 42 41 bytes

s=>![...s].some((e,i)=>s%e|s.search(e)<i)

Takes input as a string and returns true or false as appropriate. Edit: Saved 1 byte thanks to @RickHitchcock. Other versions:

Takes input as a string and returns 0 or 1 (i.e. logical inverse) for 40 bytes:

s=>/(.).*\1/.test(s)|[...s].some(e=>s%e)

Takes input as a number and returns 0 or 1 for 43 bytes:

n=>/(.).*\1/.test(n)|[...''+n].some(e=>n%e)

Takes input as a number and returns 1 or 0 for 45 bytes:

n=>!/(.).*\1/.test(n)&![...''+n].some(e=>n%e)

• I was unfamiliar with the \n option for back-referencing. +1. You can move the test logic to the some method to save a byte: s=>![...s].some((e,i)=>s%e|s.search(e)<i) – Rick Hitchcock Jul 4 '17 at 14:09
• When I used [...new Array(9999999)].map((_,n)=>n+1+"").filter(s=>![...s].some((e,i)=>s%e|s.search(e)<i)).length I got 5081 instead of the expected 548, so this is not correct as written. Really tight code, though. – CR Drost Jul 5 '17 at 17:25
• Sorry, I retract my comment about this not being correct. My test code is not correct because the original poster expects that zeros have already been filtered out. With an extra .filter(x => x.indexOf('0')===-1) this returns 548 as promised. – CR Drost Jul 5 '17 at 18:01

# Jelly, 6 4 bytes

Dg⁼Q

Try it online!

### How it works

Dg⁼Q  Main link. Argument: n

D     Decimal; convert n to base 10.
g    Take the GCD of each decimal digit k and n.
For each k, this yields k if and only if k divides n evenly.
Q  Unique; yield n's decimal digits, deduplicated.
⁼   Test the results to both sides for equality.

• There's also gQV= if you prefer an ASCII-only solution. – Dennis Jul 4 '17 at 16:00

# Python 3, 54 bytes

Returns False when a number is a Lynch-Bell number. Takes strings as input. Came up with on my own but very similar to Rod's. I would've commented under his post but I don't have any reputation yet.

lambda s:len({*s})<len(s)+any(int(s)%int(c)for c in s)

Try it online!

• Welcome to PPCG! – Stephen Jul 4 '17 at 21:27
• Welcome! Like Rod's, your function throws an exception on input "10". – CR Drost Jul 5 '17 at 17:34
• @CRDrost "You will be given a positive, whole number (that will never contain a 0) as input." – C McAvoy Jul 5 '17 at 19:32
• Right, I've posted comments everywhere else I complained about this, but I apparently missed this one. Sorry, retracted! – CR Drost Jul 5 '17 at 19:36
• @CRDrost No worries! – C McAvoy Jul 5 '17 at 20:01

# Jelly, 8 bytes

D⁼QaDḍ$Ạ  Try it online! # PHP, 62 48 bytes while($i=$argn[$k++])$r|=$argn%$i|$$i++;echo!r;  Run as pipe with -nR or test it online. Empty output for falsy, 1 for truthy. breakdown while(i=argn[k++]) # loop through digits r|= # set r to true if argn%i # 1. number is not divisible by i |$$i++; # 2. or digit has been used before echo!$r;                # print negated $r  # Haskell, 61 bytes (#)=<<show (d:r)#n=notElem d r&&mod n(read[d])<1&&r#n _#_=0<3  Defines an anonymous function (#)=<<show which, given a number, returns True or False. • This function fails on the input 10. – CR Drost Jul 5 '17 at 17:17 • Sorry, I am wrong about that -- I missed that you're not required to provide any answer for inputs that have 0s in them. – CR Drost Jul 5 '17 at 18:02 # 05AB1E, 4 bytes ÑÃÙQ  Try it online! Same algorithm as this answer to a related question. # 05AB1E, 8 bytes SÖP¹DÙQ*  Uses the 05AB1E encoding. Try it online! # Mathematica, 57 bytes Tr@Boole[IntegerQ/@Union[s=#/IntegerDigits@#]]==Length@s&  • You can save numerous bytes if you use the builtin IsLynchBellNumber – Okx Jul 4 '17 at 14:53 • why don't you make the same offer to Martin? – J42161217 Jul 4 '17 at 15:00 • @Okx but it's less fun that way. – QBrute Jul 4 '17 at 21:57 • @QBrute Can you take a joke? – Okx Jul 4 '17 at 22:02 • @Okx It would have been more believable as LynchBellNumberQ. ;) – Martin Ender Jul 5 '17 at 5:20 # Python 2, 66 bytes This is a solution in Python 2, whose whole purpose is to output True for truthy and False for falsy: lambda n:len(set(n))==len(n)and not any((int(n)%int(x)for x in n))  Try it online! ## Haskell, 260241201 162 bytes f([x])=1<2 f(x:xs)=not(xelemxs)&&(f xs) r n i= nmod(read[(show n!!i)]::Int)==0 q n 0=r n 0 q n i=r n i&&q n(i-1) p n=length(show n)-1 s n=q n(p n)&&f(show n)  Explanation f ([x]) = True f function checks for f (x:xs) = not(x elem xs) && (f xs) repeated digits r n i = n mod (read [(show n !! i)] :: Int) == 0 checks whether num is divisible by i digit q n 0 = r n 0 checks wether n divisible q n i = r n i && q n (i-1) by all of its digits p n = length (show n) - gets length of number s n = (q n (p n)) && (f (show n)) sums it all up!!!  Have significantly shortened thanx to Laikoni • Welcome to PPCG and Haskell golfing in particular! This answer can be considerably shortened by removing superfluous spaces, e.g. the ones around the equal signs or next to parenthesis. – Laikoni Jul 5 '17 at 12:40 • You might also be interested in Tips for golfing in Haskell and the Guide to Golfing Rules in Haskell. – Laikoni Jul 5 '17 at 12:43 • @Laikoni Thanx for your advice! I'm looking into it – Sergii Martynenko Jr Jul 5 '17 at 13:51 # Japt, 15141110 9 bytes ì®yUÃ¥Uìâ  Try it • ©! -> « for -1 byte – Justin Mariner Sep 11 '17 at 17:35 • Thanks, @JustinMariner; don't know how that went so long without being spotted! I found a shorter solution, though. – Shaggy Sep 11 '17 at 19:11 # Neim, 9 bytes 𝐮ℚ₁𝐅₁𝕌₁ℚ𝕒  Try it online! -2 thanks to Okx. Hmm, there's a nice symmetry... oO.O.O.Oo • You can golf 𝐂D𝐮𝔼 to 𝐮ℚ (uniquify, check for equality ignoring types) – Okx Jul 4 '17 at 12:11 • Still room for golfing there ;) – Okx Jul 4 '17 at 12:19 • @Okx Hmm...I don't see anything particularly interesting there. – Erik the Outgolfer Jul 4 '17 at 12:26 # Perl 6, 27 bytes {$_%%.comb.all&&[!=] .comb}

Try it online!

• .comb is a method which, when given no arguments, splits a string into its individual characters. A number is implicitly converted into a string, and so .comb returns its digits.
• .comb.all is an and-junction of all of the digits.
• $_ %% .comb.all is an and-junction of the divisibility of the input argument $_ by all of its digits. For example, if $_ is 123, the junction is all(True, False, True), which collapses to False in a truthy context. • [!=] .comb reduces the digits of the input argument with the != operator, which evaluates to True if the digits are all different. # Retina, 37 bytes (.).*\1 0 . <$&$*1>$_$* <(1+)>\1+ ^$

Try it online! Link includes test cases. Explanation: The first stage replaces any duplicate digit with a zero. The second stage replaces each digit with its unary representation followed by the unary representation of the original number. The third stage then computes the remainder of the division of original number by each non-zero digit. If the number is a Lynch-Bell number then this will delete everything and this is tested for by the final stage.

# Ruby 2.4, 42 bytes

->x{(r=x.digits)|[]==r&&r.none?{|f|x%f>0}}

(No TIO yet, sorry)

## CJam, 17 bytes

CJam is the Java of golfing languages. It's even interpreted in Java!

{_Ab__L|=@@f%:+>}

### Explanation:

{   e# Stack:              3915
_   e# Duplicate:          3915 3915
Ab  e# Digits in base 10:  3915 [3 9 1 5]
__  e# Duplicate twice:    3915 [3 9 1 5] [3 9 1 5] [3 9 1 5]
L|  e# Remove duplicates:  3915 [3 9 1 5] [3 9 1 5] [3 9 1 5]
=   e# Test equality:      3915 [3 9 1 5] 1
@@  e# Rotate twice:       1 3915 [3 9 1 5]
f%  e# Modulo each:        1 [0 0 0 0]
:+  e# Sum:                1 0
>   e# Greater than:       1
}   e# Output:             1 (truthy)

## VBScript, 177 bytes

Hey all, this is my very first CG post, and first attempt, so hope I followed all the rules...

Function L(s)
dim i,j,k,m,n
j = Len(s)
redim a(j)
n = 0
for i = 0 to j-1
A(i) = Mid(s,i+1,1)
m = m + s Mod A(i)
if j = 1 then
else
for k = 0 to i - 1
if A(i)  = A(k) then n = n + 1
next
end if
next
if m + n = 0 then L = "y" else L = "n"
End Function

This can be run from Notepad by adding a line at the end

Msgbox L(InputBox(""))

And then saving it as .vbs, then double click.

Explanation:

Function L(s)                  'creates the function "L" taking test number as input
dim i,j,k,t,m,n                'variables
j = Len(s)                     '"j" gets length of test number
redim a(j)                     'creates array "a", size is length of test number
n = 0                          'sets repeat character counter "n" to zero
for i = 0 to j-1               'for length of string
A(i) = Mid(s,i+1,1)         'each array slot gets one test number character
m = m + s Mod A(i)          '"m" accumulates moduli as we test divisibility of each digit
if j = 1 then               'if test number is of length 1, it passes (do nothing)
else                        'otherwise, gotta test for repeats
for k = 0 to i - 1     'for each digit already in array, test against current digit
if A(i)  = A(k) then n = n + 1
'repeat char counter "n" stores no of repeats
next                   'proceed through array looking for repeat
end if
next                           'test next digit for divisibility and repeats
if m + n = 0 then L = "y" else L = "n"
'check for any repeats and moduli,
'then return yes or no for LynchBelledness
End Function

VBScript is a bit of blunt instrument for golfing, but hey, I haven't learned Ruby yet...

• Can't you remove some of the whitespace like 'L="y"' – Okx Jul 8 '17 at 20:01
• Technically, yes! I shoulda done that...btw, i'm looking at codegolf languages that might be cool to learn, but for most, the documentation is minimal to non-existent...can anyone recommend a good language that is well documented? Was trying out "Actually/Seriously" but hit some obstacles due to lack of doc.... – aAaa aAaa Jul 11 '17 at 0:07

# PHP, 51 bytes

prints zero for true and one for false

for(;$c=$argn[$i++];$$c=1)t|=$$c||$argn%$c;echo$t;

Try it online!

# PHP, 62 bytes

prints zero for true and one for false

for($a=$argn;$c=$a[$i];)$t|=strpos($a,$c)<+$i++||$a%$c;echo$t;

Try it online!

# Pyth, 10 bytes

qiRQKjQT{K

Verify all the test cases.

## How?

qiRQKjQT{K  ~ Full program.

jQT    ~ The list of decimal digits of the input.
K       ~ Assign to a variable K.
iRQ        ~ For each decimal digit...
i Q          ~ ... Get the greatest common divisor with the input itself.
{K  ~ K with the duplicate elements removed.
q           ~ Is equal? Output implicitly.

# Pyth, 11 bytes

&!f%sQsTQ{I

Verify all the test cases.

## How?

&!f%sQsTQ{I  ~ Full program, with implicit input.

f     Q    ~ Filter over the input string.
%sQsT     ~ The input converted to an integer modulo the current digit.
~ Keeps it if it is higher than 0, and discards it otherwise.
!           ~ Negation. If the list is empty, returns True, else False.
&        {I  ~ And is the input invariant under deduplicating? Output implicitly.

# Perl 5, 34 bytes

33 bytes of code + 1 for -p flag

$n=$_;$\|=$n%$_|$k{$_}++for/./g}{  Try it online! Outputs 0 for truthy, any other number for falsy # Kotlin 1.1, 9866 59 bytes {i->i.none{i.toInt()%(it-'0')>0}&&i.length==i.toSet().size}  ## Beautified {i -> // None of the digits are not factors i.none { i.toInt() % (it-'0') > 0 } // AND && // None of the digits are repeated i.length == i.toSet().size }  ## Test var L:(String)-> Boolean = {i->i.none{i.toInt()%(it-'0')>0}&&i.length==i.toSet().size} data class TestData(val input: String, val output: Boolean) fun main(args: Array<String>) { var inputs = listOf( TestData("7", true), TestData("126", true), TestData("54", false), TestData("55", false), TestData("3915", true) ) for (test in inputs) { if (L(test.input) != test.output) { throw AssertionError(test.toString()) } } println("Test Passed") }  # APL (Dyalog Unicode), 24 bytes {((,⍵)≡∪⍵)×∧/0=(⍎¨⍵)|⍎⍵}  Try it online! Simple Dfn, can probably be golfed a bit more. Yield standard APL booleans 1 for truthy, 0 for falsy. It's worth to mention that the function takes the arguments as strings rather than ints. ### How: {((,⍵)≡∪⍵)×∧/0=(⍎¨⍵)|⍎⍵} ⍝ Dfn, argument ⍵. ⍎⍵ ⍝ Convert ⍵ to integer | ⍝ Modulus (⍎¨⍵) ⍝ Each digit in ⍵ 0= ⍝ Equals 0? Returns a vector of booleans ∧/ ⍝ Logical AND reduction × ⍝ multiplied by (the result of) ( ∪⍵) ⍝ unique elements of ⍵ ≡ ⍝ Match (,⍵) ⍝ ⍵ as a vector; the Match function then returns 1 iff all digits in ⍵ are unique  # Julia 1.0, 39 bytes f(x,d=digits(x))=rem.(x,d)==0*unique(d)  rem.(x,d) is a vector containing the remainders after dividing x by each digit in x. 0*unique(d) is a vector with length equal to the number of unique digits, with all zero values. Check if they are equal. Try it online! # ruby -n, 40 bytes p gsub(/./){$'[$&]||$_.to_i%\$&.hex}<?0*8

Try it online!

Read in the number as a string. Substitute each character (digit) with a subsequent occurrence of that character, if present, or the whole number modulo that digit. This will result in a string of only 0s if and only if this is a Lynch-Bell number. Why? If there's a repeated digit, every instance of the last stays the same, and since the input doesn't contain zeroes that means a non-zero digit. Otherwise, we're just checking whether every digit evenly divides the number.

Since there are no 8-or-more-digit Lynch-Bell numbers (formal proof: OEIS says so), checking whether the resulting string is lexicographically earlier than the string '00000000' is equivalent to checking whether it's all zeroes.

# R, 86 bytes

x=scan(,'');a=as.double;all(table(utf8ToInt(x))==1)&&all(!a(x)%%a(el(strsplit(x,""))))

Takes input as a string. I certainly feel like this is golfable.

Try it online!


text:
# Homework Help: Limits of sequences as x heads to infinity

1. Oct 23, 2012

### BigJon

cn= (4n)/(n+4n^(1/n))

When i set it up i think i should use l'hopital but im confused what to do with the 4n^(1/n) term.

an=(7^(2n))/(n!)

I know this is a geometric sequence and top and bottom increase initially then tend to 0, but im lost on how to show the work. should i expand the factorial or how would i use this with the squeeze theorem

2. Oct 23, 2012

### Ray Vickson

Does 4n^(1/n) mean 4[n^(1/n)], or does it mean (4n)^(1/n). If one reads it using standard rules, what you have written is 4[n^(1/n)]. So, what is the limit of n^(1/n)? [Hint: take logarithms.]

RGV

3. Oct 23, 2012

### BigJon

This is what it looks like sorry for confusion

#### Attached Files:

• ###### sequence.JPG
File size:
3.3 KB
Views:
67
4. Oct 23, 2012

### Ray Vickson

There was no actual confusion; what you wrote is what you meant. (However, that is often not the case on this Forum, so that is why I asked.)

RGV

5. Oct 24, 2012

### BigJon

ln(n^(1/n))
(1/n)ln(n)=ln(n)/n

lim x->infin of ln(n)/n ->0 using l'hopitals rule

I dont understand did you apply ln to all the terms?

6. Oct 24, 2012

### Ray Vickson

I did not apply ln to anything---you did. So, given what you just did above, what can you say about whether or not n^(1/n) has a limit, and if so, what that limit is? Why does the answer to this question simplify the original problem?

RGV

7. Oct 24, 2012

### BigJon

So i put it into the form of lnx/x use lhopitals then it goes to 4/1+((1/x)/(x)) limit of this as it goes to inifintiny becomes 4

8. Oct 24, 2012

### Ray Vickson

Once you have the form above, you do not need l'Hospital any more. Do you see why?

RGV

9. Oct 24, 2012

### BigJon

Well i already took it once so i dont need to take it again. i just take limits after that.

What i need to know is how can you apply the Ln to just n^(1/n) without applying it to the other n in the denominator or 4n in the numerator.

10. Oct 24, 2012

### Ray Vickson

Your denominator has two terms: n and n^(1/n). You need to know how the denominator behaves for large n, and that has nothing at all to do with l'Hospital's rule or anything like it. How does n behave when n → ∞? How does n^(1/n) behave when n → ∞? Do, how does the denominator behave when n → ∞? Furthermore, if you re-write your fraction as
$$\frac{4}{1 + r(n)},$$
where
$$r(n) = \frac{1}{n} n^{1/n},$$
it is easy to see what is the limit of r(n) as n → ∞. If that limit is L, the whole fraction has limit 4/(1+L).

Just as you do not need l'Hospital to do lim (2x)/x [because for x ≠ 0 it is just equal to 2], so you do not need l'Hospital here.

RGV


text:
zbMATH — the first resource for mathematics

The geometry of moduli spaces of pointed curves, the tensor product in the theory of Frobenius manifolds and the explicit Künneth formula in quantum cohomology. (English) Zbl 0918.14011
Bonner Mathematische Schriften. 312. Bonn: Univ. Bonn, Mathematisch-Naturwissenschaftliche Fakultät, 95 p. (1998).
This thesis develops further the results of an article by R. Kaufmann, Yu. Manin and D. Zagier [Commun. Math. Phys. 181, No. 3, 763-787 (1996; Zbl 0890.14011)] and their applications.
It has three chapters. The first one discusses the intersection of strata classes in $$\overline M_{g,n}$$ and provides the formulae for the intersection matrices in cohomology of $$\overline{M_{0,n}}$$ (moduli space of pointed curves of genus 0), and for Weil-Petersson volumes. These results are used in chapter two to define the tensor product of the pointed Frobenius manifolds. In chapter 3 the formulae from chapters 1 and 2 are used to derive the explicit Künneth formula for quantum cohomology. Examples of products of two and three 3-dimensional Calabi-Yau manifolds are discussed at the end.

MSC:
 14H10 Families, moduli of curves (algebraic) 14F99 (Co)homology theory in algebraic geometry 55N20 Generalized (extraordinary) homology and cohomology theories in algebraic topology 81T30 String and superstring theories; other extended objects (e.g., branes) in quantum field theory


text:
# Previous such prime

$2017=2^{11}-2^5+1$

Given the equality above, what is the largest prime number $p\, (<2017)$ that could be represented as

$p=2^a \pm 2^b \pm 1?$

×


text:
# (guest@joequery.me)~ $| # Learning C (Part 2): Types and Expressions (This post is part of the learning c series.) In this article, I will note what I feel are the non-obvious information related to C types, operators, and expressions. ## Data Types • char: a single byte. Holds a single character. • int: an integer • float: single-precision floating point • double: double-precision floating point ### Qualifiers The qualifiers short or long can be applied to an integer. • short and int must be at least 16 bits in size, but int may be larger than short depending upon hardware and implementation. Also, short <= int. • long is at least 32 bits. Also, int <= long. Usage can be seen below:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include int main(){ short int x = 10; // int can actually be omitted here short y = 10; // zu is size_t type specifier printf("%zu\n", sizeof x); printf("%zu\n", sizeof y); long int lx = 10; long ly = 10; printf("%zu\n", sizeof lx); printf("%zu\n", sizeof ly); return 0; }  2 2 8 8  Note that the output is in bytes, so see that sizeof x is 16 bits and sizeof lx is 64 bits. The qualifiers signed or unsigned can be used with a char or any integer type. • unsigned numbers are always ≥ 0. • unsigned numbers obey laws of arithmetic$\mod{2^n}\$, where n is the number of bits in the type.
• For example, for an 8-bit unsigned char type, the possible values are 0-255.
• For an 8-bit signed char type, the possible values are -128-127.

• long double specifies extended floating point precision.

• float <= double <= long double
• The sizes of the above could be distinct or similar. It's implementation defined.

Here's an example experimenting with these qualifiers.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include int main(){ // -------------------------------------------------- // Messing with size qualifiers // -------------------------------------------------- short sx = 10; int ix = 10; long lx = 10; char *fmt1 = "short: %zu, int: %zu, long: %zu\n"; printf(fmt1, sizeof sx, sizeof ix, sizeof lx); float fy = 10.0; double dy = 10.0; long double ldy = 10.0; char *fmt2 = "float: %zu, double: %zu, long double: %zu\n"; printf(fmt2, sizeof fy, sizeof dy, sizeof ldy); // -------------------------------------------------- // Messing with signed/unsigned qualifiers // -------------------------------------------------- unsigned char c = -1; unsigned long lc = -1; printf("c: %u, lc: %lu\n", c, lc); return 0; }
short: 2, int: 4, long: 8
float: 4, double: 8, long double: 16
c: 255, lc: 18446744073709551615

## Constants and literals

• int - 1234
• long - 123456789L
• unsigned - 123U
• unsigned long - 123UL

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include int main(){ int theint = 123; printf("%d\n", theint); long thelong = 123456789L; printf("%ld\n", thelong); unsigned theuint = 123U; printf("%u\n", theuint); unsigned long theulong = 123456789UL; printf("%lu\n", theulong); double thedouble = 123e-2; printf("%f\n", thedouble); int thehex = 0xA88BCF; printf("%x\n", thehex); char thechar = 'A'; // single, not double quotes printf("c as char: %c\n", thechar); printf("c as int: %d\n", thechar); return 0; }
123
123456789
123
123456789
1.230000
a88bcf
c as char: A
c as int: 65

String literals have a null character ('\0') at the end.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include void print_str(char *s); int main(){ char *mystr = "Hello"; print_str(mystr); return 0; } void print_str(char *s){ int i=0; char c; while(c = *s++) printf("%c\n", c); if(c == '\0') // '\0' is not a printable character, so we need to print something // ourselves if we want to see it. printf("\\0\n"); }
H
e
l
l
o
\0

Note: 'x' != "x"

## Enums for symbol comparison

Enums are a great way to use symbols to represent constant, related data without the use of a define. Enums allow for semantic, readable comparisons with symbols when their value doesn't necessarily matter.

These concepts are described in the following example:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include enum category { DOG, HUMAN, CAT }; struct mammal { char *name; enum category c; }; void find_the_mammal(struct mammal *mammals, enum category mammal_type, size_t n); int main(){ struct mammal mammals[3]; mammals[0] = (struct mammal){"Joseph", HUMAN}; mammals[1] = (struct mammal){"Odin", CAT}; mammals[2] = (struct mammal){"LUCY", DOG}; find_the_mammal(mammals, HUMAN, 3); find_the_mammal(mammals, CAT, 3); find_the_mammal(mammals, DOG, 3); return 0; } void find_the_mammal(struct mammal *mammals, enum category mammal, size_t n){ int i; for(i=0; i
Joseph
Odin
LUCY

## Implicit and explicit type conversions

When performing an operation where the items being operated on are of different types, they are converted to a common type before the operation occurs.

For example, take the following simple program:

 1 2 3 4 5 6 7 #include int main(){ int x = 10; double y = 20.0; printf("%f\n", x+y); return 0; }
30.000000

The integer value of x was implicitly converted to a double when added to the double y. This conversion was "temporary" in that the variable x was not effected at all. x still remains an integer after the printf() statement has finished.

In general, implicit conversions such as the one above will make the smaller data type match the larger one. This is because there is no data loss going from an int to a float, but there is definitely data loss going from float to int via truncation!

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include #include int main(){ // You need a grade average of 70 after rounding to graduate int graduation_threshold = 70; float your_grade = 69.9999; float your_grade_rounded = round(your_grade); printf("Your rounded grade as a double: %.2f\n", your_grade_rounded); int your_grade_as_int = your_grade; int your_grade_as_int_rounded = round(your_grade_as_int); if(your_grade_as_int_rounded >= graduation_threshold){ printf("You graduated. Congrats!\n"); } else{ printf("You failed! Oh no!\n"); } printf("Your final grade: %d\n", your_grade_as_int_rounded); return 0; }
Your rounded grade as a double: 70.00
You failed! Oh no!

### Chars are just numbers!

 1 2 3 4 5 6 7 #include int main(){ char c = 'A'; c++; printf("%c\n", c); return 0; }
B

### Implicit conversions

Suppose you have an operator that takes two numeric operands. The C standard specifies the following rules for conversions, in order (this is an exact quote of the standard):

1. First, if either operand is long double, the other is converted to long double.
2. Otherwise, if either operand is double, the other is converted to double.
3. Otherwise, if either operand is float, the other is converted to float.
4. Otherwise, the integral promotions are performed on both operands; then, if either operand is unsigned long int, the other is converted to unsigned long int.
5. Otherwise, if one operand is long int and the other is unsigned int, the effect depends on whether a long int can represent all values of an unsigned int; if so, the unsigned int operand is converted to long int; if not, both are converted to unsigned long int.
6. Otherwise, if one operand is long int, the other is converted to long int.
7. Otherwise, if either operand is unsigned int, the other is converted to unsigned int.
8. Otherwise, both operands have type int.

Comparison between signed and unsigned values are machine-dependent.

Note: "integral promotion" is a process that occurs when a char, short, or enum object are promoted to either int or unsigned int when used in an expression. If an int can represent the value of being converted, the value is converted to an int for the expression. Otherwise, it is converted to unsigned int.

Rules 1-3, and 6-8 were demonstrated by example 5 above.

The rules unsigned concerning integers are much more interesting, and they have very important implications! Consider a machine with a 32 bit int and 64 bit long along with the following example:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include int main(){ // On my computer, this prints 32 and 64. It may be different on your // computer! printf("sizeof unsigned int: %zu\n", sizeof(unsigned int)*8); printf("sizeof long: %zu\n", sizeof(long)*8); // Note that long/short, when by themselves, act as shorthand for // "long int" and "short int" respectively. printf("sizeof long int: %zu\n", sizeof(long int)*8); if(-1L < 1U){ printf("-1 < 1. Duh!\n"); } else{ printf("-1 > 1?! WTF?!\n"); } if(-1L < 1UL){ printf("-1 < 1. Duh!\n"); } else{ printf("-1 > 1?! WTF?!\n"); } return 0; }
sizeof unsigned int: 32
sizeof long: 64
sizeof long int: 64
-1 < 1. Duh!
-1 > 1?! WTF?!

Let's explain this behavior using the rules listed above.

#### -1L < 1U

In the first comparison, we are comparing a long with an unsigned int. Rule 5 tells us what we should expect when an unsigned int and a long are operands together:

Otherwise, if one operand is long int and the other is unsigned int, the effect depends on whether a long int can represent all values of an unsigned int; if so, the unsigned int operand is converted to long int; if not, both are converted to unsigned long int.

So the question becomes: Can a 64 bit long represent all the values of a 32 bit unsigned int? A long has to be able to represent both positive and negative numbers, whereas an unsigned int only has to represent positive numbers. So if the largest possible positive long value is greater than or equal to the largest possible unsigned int value, the standard says the unsigned int will be converted to long.

Let's ask <limits.h> whether a 64 bit long can represent all the values of a 32 bit unsigned int.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include #include // This is by definition #define UINT_MIN 0 int main(){ printf("UINT_MIN: %u\n", UINT_MIN); printf("UINT_MAX: %u\n", UINT_MAX); printf("LONG_MAX: %ld\n", LONG_MAX); printf("LONG_MIN: %ld\n", LONG_MIN); if(LONG_MIN <= UINT_MIN && LONG_MAX >= UINT_MAX){ printf("long can represent all values of unsigned int\n"); } return 0; }
UINT_MIN: 0
UINT_MAX: 4294967295
LONG_MAX: 9223372036854775807
LONG_MIN: -9223372036854775808
long can represent all values of unsigned int

So the answer is yes, a long can represent all values of an unsigned int, thus the less-than operator -1L < 1UL will cause unsigned int to be converted to a long during the comparison. Let's see what the result of conversion would be.

 1 2 3 4 5 6 #include int main(){ long l = (long) 1U; printf("%ld\n", l); return 0; }
1

This behavior isn't anything unexpected! But now, it's time for the fun part.

#### -1L > 1UL

Rule 4 in the conversion steps says

Otherwise, the integral promotions are performed on both operands; then, if either operand is unsigned long int, the other is converted to unsigned long int.

So during the evaluation of the expression -1L > 1UL, integral promotion is performed. Remember, integral promotion is just taking the smaller int types, such as char and short, and converting them to int or unsigned int. So, since we are dealing with larger integer types, integral promotion does not occur in this example.

The second part of Rule 4, though, states that if either operand is an unsigned long, the other operand is converted to an unsigned long. Thus, in the expression -1L > 1UL, the operand -1L will be converted to an unsigned long. Let's see what converting a negative long to an unsigned long looks like.

  1 2 3 4 5 6 7 8 9 10 #include #include int main(){ unsigned long ul = (unsigned long) -1L; printf("%lu\n", ul); // Compare printf("%lu\n", ULONG_MAX); return 0; }
18446744073709551615
18446744073709551615

The C standard actually mandates that -nUL == ULONG_MAX-n+1 for some integer n holds true for any standards-compliant compiler - this result is not machine dependent. Thus, converting a negative, signed long to an unsigned long yields a VERY big number. Identical behavior occurs for UINT.

So, for the comparison of -1L > 1UL, Rule 4 states that -1L is converted to an unsigned long, and we have seen that such a conversion results in a very large number. So now, it makes sense that -1L > 1UL, since the largest unsigned long is certainly larger than the number 1!

### Explicit conversions

As you may have noticed in previous examples, we can explicitly convert data via a "cast". You simply prefix an expression with (thetype), and that expression will be converted to that type.

Consider this example, which will provide a compile-time warning due to formatter mismatch:

 1 2 3 4 5 6 #include int main(){ int i = 15; printf("The value: %.2f\n", i); return 0; }
ex13.c: In function ‘main’:
ex13.c:4:5: warning: format ‘%f’ expects argument of type ‘double’, but argument
2 has type ‘int’ [-Wformat]

The value: 0.00

Instead of creating another variable to facilitate an implicit int to float conversion, we can explicitly convert the data ourselves.

 1 2 3 4 5 6 #include int main(){ int i = 15; printf("The value: %.2f\n", (float)i); return 0; }
The value: 15.00
`

## (This post is part of the learning c series.)

Date published - November 25, 2013


text:
# I need some help-Trig Identities

Prove the following identities:

(cos A = cos B)^2 + (sin A + sin B)^2 = 2[1+cos(A-B)]

I'm really a mess at this stuff. I missed a few important days and fell behind, so I don't reeeally know what to do when things start getting squared and whatnot., but I tried!

Left Side
(cos A + Cos B)^2 + (sin A + sin B)^2
(cos(^2)A+cos(^2)B = Sin(^2)A+sin(^2)B
(cos (^2)A+cos(^2)B+ (1+-cos(^2)A + (1+-cos(^2)B)
2

Right Side
2+2cos(A-B)
2(cosAcosB+sinAsinB) +2

But that's as far as I can get. I can't find a way to make both sides equal, and I'm not even sure if my left side is correct...

Last edited:

First, do you know what $$(a+b)^2=...???????$$ you have not expanded well. Give it another shot.

$$(cosA+cosB)^2=...?....$$

$$(sinA+sinB)^2=....?$$

After you expand this, remember also that:

$$cos^2A+sin^2A=1, and, sin^2B+cos^2B=1$$

And somewhere in between you will end up with sth like this

$$2+ 2cosBcosA+2sinAsinB$$ now the answer should be obvious, right?

Last edited:
Urk, I thought that because in my third step on the left I had (cos^2A) and (-cos ^2A), that they would cancel...?

$$(sinA+sinB)^2=sin^2A+2sinAsinB+sin^2B....?$$

also

$$(cosA+cosB)^2=cos^2A+2cosAcosB+cos^2B$$

Can you go from here now?

Just use the hints that i gave you on my post #2

also, another hint, altough you should have figured this out by yourself

$$cos(A-B)=cosAcosB+sinAsinB$$

I think I can I didnt know that before, I will try to work it out now!

I think I can I didnt know that before, I will try to work it out now!

I wrote in there everything you need to do that problem, you only need to put all the hints together.

I got it, Thank you!

I got it, Thank you!

You're welcome. THis is what PF is for!