text:
A community for students. Sign up today

Here's the question you clicked on:

anonymous 5 years ago 6x^2-9x+5=0 quadratic formula

• This Question is Closed
1. anonymous

$x=(-b \pm \sqrt{b ^{2}-4ac})/2a$

2. anonymous

a= 6, b=-9, c=5

3. anonymous

Hint: 6x^2-9x+5 can be factored.

4. anonymous

Sorry. The hint is not true. I should have verified prior to posting.

5. anonymous

Yeah It's okay. I tried but it didn't work.

6. anonymous

so, how about the quadratic formula?

7. anonymous

Thanks it helped a lot ! I was figured it out before but everything was in a big mess and in the wrong order. But I've gotten the answer, Thanks for the correct formula.

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy


text:
# How do you find the slope of the tangent line for f(x) = 3x^2 at (1,3)?

Aug 29, 2015

The slope is $6$.

#### Explanation:

I will assume that you have not yet been taught the rules (shortcuts) for finding derivatives. So, we will use a definition.

The slope of the line tangent to the graph of the function $f$ at the point $\left(a , f \left(a\right)\right)$ can be defined in several ways (or using several notations). Two of the more common are:

${\lim}_{x \rightarrow a} \frac{f \left(x\right) - f \left(a\right)}{x - a}$ $\text{ }$ OR $\text{ }$ ${\lim}_{h \rightarrow 0} \frac{f \left(a + h\right) - f \left(a\right)}{h}$

(Each author,teacher,presenter needs to choose one definition as the 'official' definition. Many will immediately mention other possibilities as 'equivalents'.)

For this question we have $f \left(x\right) = 3 {x}^{2}$ and $a = 1$

We'll find:

${\lim}_{x \rightarrow a} \frac{f \left(x\right) - f \left(a\right)}{x - a}$
(Note that substitution gets us the indeterminate form $\frac{0}{0}$. We have some work to do.)

${\lim}_{x \rightarrow 1} \frac{f \left(x\right) - f \left(1\right)}{x - 1} = {\lim}_{x \rightarrow 1} \frac{3 {x}^{2} - 3}{x - 1}$

$= {\lim}_{x \rightarrow 1} \frac{3 \left({x}^{2} - 1\right)}{x - 1}$

$= {\lim}_{x \rightarrow 1} \frac{3 \left(x + 1\right) \left(x - 1\right)}{x - 1}$

The expression whose limit we want is equal to $3 \left(x + 1\right)$ for all $x$ other than $x = 1$. The limit doesn't care what happens when $x$ is equal to $1$, it wants to onow what happens when $x$ is close to $1$, so we get:

${\lim}_{x \rightarrow 1} \frac{3 \left(x + 1\right) \left(x - 1\right)}{x - 1} = {\lim}_{x \rightarrow 1} 3 \left(x + 1\right) = 6$

The slope of the tangent we were asked about is $6$.

Short method

For $f \left(x\right) = 3 {x}^{2}$, we get $f ' \left(x\right) = 3 \cdot 2 {x}^{2 - 1} = 6 x$

The slope of the tangent at $1$ is $f ' \left(1\right) = 6 \left(1\right) = 6$

format: plain


text:
# Discrete wavelet structure and discrete energy of classical plane light waves

@article{Zhang2020DiscreteWS,
title={Discrete wavelet structure and discrete energy of classical plane light waves},
author={Xingchu Zhang and Wei-long She},
journal={arXiv: Optics},
year={2020}
}
• Published 30 May 2020
• Physics
• arXiv: Optics
In this letter, the wavelet transform is used to decompose the classical linearly polarized plane light wave into a series of discrete Morlet wavelets. It is found that the energy of the light wave can be discrete, associated with its discrete wavelet this http URL is also found that the changeable energy of a basic plane light wave packet or wave train of wave vector $\mathord{\buildrel{\lower3pt\hbox{$\scriptscriptstyle\rightharpoonup$}}\over k}$ and with discrete wavelet structure can be… Expand

#### References

SHOWING 1-10 OF 41 REFERENCES
The norms and variances of the Gabor, Morlet and general harmonic wavelet functions
• Mathematics
• 2003
Abstract This paper deals with certain properties of the continuous wavelet transform and wavelet functions. The norms and the spreads in time and frequency of the common Gabor and Morlet waveletExpand
Morlet wavelets in quantum mechanics
Wavelets offer significant advantages for the analysis of problems in quantum mechanics. Because wavelets are localized in both time and frequency they avoid certain subtle but potentially fatalExpand
A wavelet multiscale method for inversion of Maxwell equations
• Mathematics
• 2009
This paper is concerned with estimation of electrical conductivity in Maxwell equations. The primary difficulty lies in the presence of numerous local minima in the objective functional. A waveletExpand
The Quantum Theory of the Emission and Absorption of Radiation
The new quantum theory, based on the assumption that the dynamical variables do not obey the commutative law of multiplication, has by now been developed sufficiently to form a fairly complete theoryExpand
The Tiger and the Shark: Empirical Roots of Wave-Particle Dualism
• Physics
• 1983
Foreword Thomas S. Kuhn Preface Notes on sources 1. Introduction Part I. The Introduction of Temporal Discontinuity, 1896-1905: 2. The electromagnetic impulse hypothesis of x-rays 3. The analogyExpand
The Conservation of Photons
WHATEVER view is held regarding the nature of light, it must. now be admitted that the process whereby an atom loses radiant energy, and another near or distant atom receives the same energy, isExpand
Interpolating wavelets for the solution of Maxwell equations in the time domain
• Physics
• 1998
A wavelet-based approach is presented for solving Maxwell equations. Full benefit is gained from the wavelets in terms of self-adaptativity of the resolution. Using interpolating wavelets allows forExpand
A Direct Photoelectric Determination of Planck's " h "
Quantum theory was not originally developed for the sake of interpreting photoelectric phenomena. It was solely a theory as to the mechanism of absorption and emission of electromagnetic waves byExpand
Evolution of the modern photon
• Physics
• 1989
The term ‘‘photon’’ represents at least four distinct models and carries different connotations for students and for practicing physicists. This reflects the long and complex historical evolution ofExpand
Demonstration of single‐electron buildup of an interference pattern
• Physics
• 1989
The wave–particle duality of electrons was demonstrated in a kind of two‐slit interference experiment using an electron microscope equipped with an electron biprism and a position‐sensitiveExpand


text:
# Measurement of the jet radius and transverse momentum dependence of inclusive jet suppression in lead-lead collisions at sqrt(s(NN)) = 2.76 TeV with the ATLAS detector

4 APC - Neutrinos
LPNHE - Laboratoire de Physique Nucléaire et de Hautes Énergies, APC (UMR_7164) - AstroParticule et Cosmologie
8 Laboratoire de Physique Corpusculaire
LPC - Laboratoire de Physique Corpusculaire - Clermont-Ferrand
Abstract : Measurements of inclusive jet suppression in heavy ion collisions at the LHC provide direct sensitivity to the physics of jet quenching. In a sample of lead-lead collisions at sqrt(s) = 2.76 TeV corresponding to an integrated luminosity of approximately 7 inverse microbarns, ATLAS has measured jets with a calorimeter over the pseudorapidity interval |eta| < 2.1 and over the transverse momentum range 38 < pT < 210 GeV. Jets were reconstructed using the anti-kt algorithm with values for the distance parameter that determines the nominal jet radius of R = 0.2, 0.3, 0.4 and 0.5. The centrality dependence of the jet yield is characterized by the jet "central-to-peripheral ratio," Rcp. Jet production is found to be suppressed by approximately a factor of two in the 10% most central collisions relative to peripheral collisions. Rcp varies smoothly with centrality as characterized by the number of participating nucleons. The observed suppression is only weakly dependent on jet radius and transverse momentum. These results provide the first direct measurement of inclusive jet suppression in heavy ion collisions and complement previous measurements of dijet transverse energy imbalance at the LHC.
Document type :
Journal articles
Domain :

http://hal.in2p3.fr/in2p3-00723484
Contributor : Emmanuelle Vernay <>
Submitted on : Friday, August 10, 2012 - 9:34:44 AM
Last modification on : Thursday, February 25, 2021 - 10:58:36 AM

### Citation

G. Aad, S. Albrand, Q. Buat, B. Clement, J. Collot, et al.. Measurement of the jet radius and transverse momentum dependence of inclusive jet suppression in lead-lead collisions at sqrt(s(NN)) = 2.76 TeV with the ATLAS detector. Physics Letters B, Elsevier, 2013, 719, pp.220-241. ⟨10.1016/j.physletb.2013.01.024⟩. ⟨in2p3-00723484⟩

Record views


text:
# Need an example of a HLSL Compute Shader

I'm finding Compute shaders very confusing. I was wondering, if I were to provide an example, and maybe one more later, if someone could demonstrate how to convert it into a Compute shader for D3D11?

Here is the example, it's just a function:

void tonemap( out float4 low, out float4 high, float3 rgb, float scale)
{
rgb = rgb*scale;
low = rgb.xyzz;
high = rgb.xyzz-saturate(rgb.xyzz);
}

There's little point in converting your example to DirectCompute. It has no need to share data between pixels, so you are actually much better off doing a global tone-map operator in a Pixel Shader.

A more interesting case would be in trying to do a local tone-map operator where pixels need to share data between them (something you can't do in a pixel shader in a single pass). That's what the classic DirectX SDK sample HDRToneMappingCS11 is doing.

Other interesting DirectCompute shaders can be found in FluidCS11, NBodyGravityCS11, and BC6HBC7EncoderCS. There are also a number of compute shaders in the MiniEngine DirectX demo.

You can look at AdaptiveTessellationCS40 for ideas as well, but it's probably not a good choice for actually implementing tessellation on modern hardware--it was intended as a way to emulate tessellation hardware for Feature Level 10.x cards.

Of course, you can also use DirectCompute for completely non-graphics related tasks. For example, the ComputeShaderSort11 sample which implements a bitonic sort.

Take a look at the BasicCompute11 for a very simple example of using DirectCompute that does a simple sum of two arrays. This sample is really more about how to do all the setup and creating the buffers, so the shader there isn't really all that useful beyond showing how to deal with double-precision data buffers.

• Thanks. Seems I need to do more reading and examine that SDK more. – user90214 Aug 22 '16 at 22:11
• It' a bit of a challenge because the DirectX SDK itself is deprecated (see MSDN). There are, however, a lot of useful things in there which is why I published a ton of it to GitHub using the Windows SDK instead of the legacy DirectX SDK. – Chuck Walbourn Aug 23 '16 at 3:48
• Thanks again :) Didn't realize you worked for Microsoft, so I really got a pro answer :) I have one more question if you don't mind: are there any types of shaders that should not be used as compute shaders? For example, are ssao-methods, bloom, lighting effects, maybe shadows all ok to use in Compute shaders, or no? – user90214 Aug 23 '16 at 15:26
• It depends entirely on the specifics of the scenario and which hardware you are using, and of course what Direct3D Feature Level you require. If you require Feature Level 11+, then using DirectCompute for post-processing generally is probably a good option. That said, if your algorithm fits within the limits of a Pixel Shader and all other things being equal then that is likely faster than using compute since the hardware is well optimized for that kind of workload. – Chuck Walbourn Aug 23 '16 at 17:16


text:
## CoconutJJ one year ago LIM{x -> inf} [sqrt( (X^2) - 3x) - x]

1. CoconutJJ

$\lim_{x \rightarrow \infty}(\sqrt{x^2-3x}-x)$

2. anonymous

$\large \lim_{x\rightarrow \infty} \sqrt{x^2-3x}-x$ simplify this by multiplying it by its conjugate?

3. CoconutJJ

I tried that, but then the denominator becomes a problem... :(

4. anonymous

$\sqrt{x^2-3x}-x \cdot \frac{\sqrt{x^2-3x}+x}{\sqrt{x^2-3x}+x}$$=\frac{(x^2-3x)+x\sqrt{x^2-3x}-x\sqrt{x^2-3x}-x^2}{\sqrt{x^2-3x}+x}$$=\frac{-3x}{\sqrt{x^2-3x}+x}$

5. anonymous

Take the derivative of $$\sqrt{x^2-3x}+x$$ and see what you get first.

6. anonymous

This limit should come out to $$-\dfrac{3}{2}$$

7. CoconutJJ

yea.. I can use l'hopital's rule, however I'm only on chapter 1 and the teacher won't allow that

8. anonymous

Ah, =_= ok.

9. anonymous

What if we... divided by the smallest power. $\large \lim_{x\rightarrow \infty} \frac{-\dfrac{3x}{x}}{\sqrt{\dfrac{x^2}{x} - \dfrac{3x}{x}} +\dfrac{x}{x}}$

10. CoconutJJ

however, when you move x into the radical it becomes x^2

11. Empty

substitute in: $x^2-3x=y^2$ solve for x to plug it in everywhere and you get: $\lim_{y \to \infty} \sqrt{y^2}-\frac{3+\sqrt{9+4y^2}}{2}$ $\frac{-3}{2}+\lim_{y \to \infty}y-\frac{\sqrt{9+4y^2}}{2}$ Not really sure if this is right path to go or not, but we're getting that -3/2 that the great wolfram alpha gives.

12. CoconutJJ

Hmm I can't seem to find the correct answer with substitution either.. I just end up with the same equation again

13. anonymous

Oh,I was forgetting a fundamental rule... $\sqrt{x^2} = |x| = x ~~~\text{as x goes towards infinity}$Therefore $\large \lim_{x\rightarrow \infty} \frac{-\dfrac{3x}{x}}{\sqrt{\dfrac{x^2}{x^2} - \dfrac{3x}{x^2}} +\dfrac{x}{x}}$$\large \lim_{\rightarrow \infty}\frac{-3}{\sqrt{1-\dfrac{3}{x}}+1}$$\large \frac{-3}{\sqrt{1}+1} = -\frac{3}{2}$

14. IrishBoy123

$$\lim_{x \rightarrow \infty}(\sqrt{x^2-3x}-x)$$ $$=\lim_{x \rightarrow \infty}(x\sqrt{1-\frac{3}{x}}-x)$$ then expand that $$sqrt$$ out via binomial

15. anonymous

When you're simplifying (idk if that's the right word for it) outside of the square root... you have to observe where x is tending to. Since x is moving towards $$\infty$$ we can divide out the terms by $$x$$ as opposed to $$-x$$ if $$x\rightarrow -\infty$$ . Does that make sense....

16. CoconutJJ

Hmm.. I think that makes sense

17. anonymous

Oh wow, typos galore in my latex format in the above post. smh. I hope you understood what I wrote up there LOL

18. anonymous

So basically dividing by $$x$$ OUTSIDE the square root $$\equiv$$ to dividing by $$x^2$$ INSIDE the square root.

19. CoconutJJ

hmmm but how did you (+x/x) I thought it was (-x)

20. anonymous

What do you mean by (+x/x)?

21. IrishBoy123

$x\sqrt{1-\frac{3}{x}}-x = \textstyle x[ 1 + \frac{1}{2}(-\frac{3}{x}) - \frac{1}{8}(\frac{3}{x})^2 +...]-x = ...$ and there's your -3/2

22. CoconutJJ

|dw:1442968334574:dw|

23. anonymous

Basically if your was $$\lim_{x\rightarrow -\infty}$$ then we would have to take the equivalent of x$$^2$$ outside the square root, which is $$-x$$ /

24. CoconutJJ

oh so we can use both positive and negative.. I guess..?

25. anonymous

$\color{red}{\sqrt{x^2} = |x| = \pm x}$ This portion is what you have to pay attention to. This little tid bit lets you know that the simplification of your function everywhere outside the square is dependant on whether your function tends to $$+\infty$$ or $$-\infty$$

26. CoconutJJ

doesn't $\sqrt{x^2-3x}$ as x-> infinity tend to positive infinity though?

27. anonymous

yes it does, but see how your variables are under the square root sign? that means the variable with the highest power under the square root is x$$^2$$, therefore you're going to divide both terms by x$$^2$$

28. CoconutJJ

hmm.. ok THANK YOU!

29. anonymous

Do you understand it fully?

30. CoconutJJ

yea.. I guess but I'm still confused on how (-x) turned to (+x/x) shown in the drawing. didn't you divide every term by +x not -x ?

31. anonymous

hint: think about how we came to simplify the original function.

32. CoconutJJ

|dw:1442969305759:dw|

33. anonymous

original function: $$\color{red}{\sqrt{x^2+3x}-x}$$ simplified function: $$\color{blue}{\dfrac{-3x}{\sqrt{x^2-3x}+x}}$$

34. anonymous

somewhere in YOUR simplification process you changed the $$+x$$ to a $$-x$$

35. CoconutJJ

ohhhhhhhhh..... I seeee... sorry.

36. anonymous

No worries, lol

37. CoconutJJ

okay.. now it makes sense

38. CoconutJJ

THANKS, once again. :)

39. anonymous

$\large \lim_{x\rightarrow \infty} \sqrt{x^2-3x}-x$$\large \lim_{x\rightarrow \infty} \sqrt{x^2-3x}-x \cdot \frac{\sqrt{x^2-3x}+x}{\sqrt{x^2-3x}+x}$$\large \lim_{x\rightarrow \infty} \frac{-3x}{\sqrt{x^2-3x}+x}$$\large \lim_{x\rightarrow \infty} \frac{-\dfrac{3x}{x}}{\sqrt{\dfrac{x^2}{x^2} - \dfrac{3x}{x^2}} +\dfrac{x}{x}}$$\large \lim_{x\rightarrow \infty}\frac{-3}{\sqrt{1-\dfrac{3}{x}}+1}$$=\boxed{-\frac{3}{2}}$


text:
# Where does the negative inductor current go during CCM at no load in synchronous converters?

As you all know, there are two primary mode of operation for dc-dc converters : CCM and DCM. At no load, the inductor current stops at zero at DCM. However, if CCM is enforced (such as Forced PWM), then inductor current can go to negative at no load or light load condition if the inductor ripple is large.

I had a simulation of a synchronous buck-boost controller at work and I saw that the current goes back to the input during negative inductor flow phase.

My questions:

1. Can I confirm that this is true and that if I use forced CCM, then my power supply would need to be one that can absorb this power during negative inductor current flow? If not, then where would this negative inductor current go?

2. Is this type of power supply common? Because there are quite a bit of synchronous converters that runs in CCM all the time out there

Thanks

There are several reasons why ensuring the buck converter remains in continuous conduction mode (CCM) in light- or no-load conditions:

1. the duty ratio is the same regardless of the load: when the buck transitions to the discontinuous mode (DCM), the relationship linking $$\V_{out}\$$ to $$\V_{in}\$$ changes and involves frequency, load and the inductor. If the converter remains in CCM in no-load conditions, you still have $$\V_{out}=DV_{in}\$$ (simplified formula).

2. there is no change in the control-to-output transfer function: the buck in voltage-mode (VM) is a second-order system in CCM and befomes an over-damped second-order in DCM. With the synchronous rectification at work, the transfer function is almost the same in light-load conditions.

3. in forward converters, typically those used in the dc-dc bricks, going into light-load conditions usually means skip cycle and lost of the auxiliary voltage: the rectified pulses are extremely narrow in skip and, without precautions, the $$\V_{cc}\$$ collapses and you need to increase the capacitor at the $$\V_{cc}\$$ pin. If the converter remains in CCM, this does not happen and the auxiliary voltage is always there.

4. finally, and this was true in post-regulated converters, like with the former mag-amp killers, synchronous rectification was letting you nicely implement leading-edge modulation to regulate the secondary outputs like a 3.3-V output made of a main 12-V one.

A typical circuit in SIMPLIS would look like this:

It simulates quickly and delivers the below waveforms:

You can see the inductor average current sets to 0 A while it remains continuous with a regulated 5-V output. During the freewheel phase involving S1, the current circulates from the ground up as with a classical diode: the current in the inductor depletes with a slope equal to $$\\frac{V_{out}}{L}\$$. When it reaches 0 A, a classical diode would spontaneously block and this is DCM. But here, S1 is bidirectional (the MOSFER operates in quadrants I and III) and the current reverses to now flow from the upper side of S1 to ground and through the load and the capacitor. At the end of the period, the controller instructs S1 to turn off. When the upper-side switch S2 turns back on, the current it sees is negative. This lasts until the inductor current crosses 0 A again and goes back to its positive peak at which moment the S2 switch turns off and S1 turns back on. The below drawing valid for a no-load situation should hopefully explain this text with less French in it : )

• Hi yes, the average inductor current is 0. but half of the period the inductor current is negative though. Where does this negative inductor current go? Won't current flowing from the inductor back to the input a problem? Jul 11 '20 at 16:30
• especially in a boost type topology. The way I see it, there is nowhere for negative current to flow besides back to the input. Jul 11 '20 at 17:25
• The source sees the neg. current when the upper-side switch turns back on as the current in the inductor is negative at the end of the freewheel session. The input capacitor sources or sinks current without problem. The low-side switch S1 "sees" the current reversing direction when the inductor current hits 0 A and goes backward, pushed by the output capacitor. It keeps circulating in the same mesh involving S1 but as S1 is bidirectional, it allows the circulation in both ways. It's only when S2 turns on again that it "sees" the negative valley. Jul 11 '20 at 19:36
• I think i understand it now. I took what you said and looked back at my simulations (boost mode of a buck boost synchronous converter). I did see that during negative inductor current flow time, the negative current goes into both the input caps and the dc source. So both the input caps and dc source help sinks the current. Let me know if I am wrong. Jul 11 '20 at 20:16
• Man! I have been searching for this information for weeks, and here it is in cogent and plain understandable language.
– RodB
Dec 31 '21 at 22:55

Energy is transferred back and forth between input and output caps via the inductor. But, as long as no power source is connected to the output, the net current flow will be from input side to output side. Or, I guess with ideal components, the net flow will be zero.

It is not super common, but some synchronous bucks actually are bidirectional converters, capable of sinking or sourcing current at the "output." So if you connect a power source to the "output," then net current actually can flow backwards to the input side.


text:
+0

# sanjay´s car

0
195
2

Sanjay´s car used 8 gallons of gasoline to travel 192 miles. On average , about how many miles per gallon did the car travel?

Guest May 19, 2017
Sort:

#1
+1

all these problems can be setup as ratios. what is a ratio, a fraction.

the answer you want is miles per gallon. so the fraction will be

m

--

g

input 192 for miles and 8 for gallons

192

-----

8

then solve the fraction. the top number goes in the box

____

8|192

Guest May 19, 2017
edited by Guest  May 19, 2017
#2
+1899
+1

Simply divide the amount of miles traveled by the amount of gallons consumed.

$${192miles\over8gallons}=24mpg$$

TheXSquaredFactor  May 19, 2017

### 12 Online Users

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners.  See details


text:
# Jensen Shannon Divergence vs Kullback-Leibler Divergence?

I know that KL Divergence is not symmetric and it cannot be strictly considered as a metric. If so, why is it used when JS Divergence satisfies the required properties for a metric?

Are there scenarios where KL divergence can be used but not JS Divergence or vice-versa?

I found a very mature answer on the Quora and just put it here for people who look for it here:

The Kullback-Leibler divergence has a few nice properties, one of them
being that $$𝐾𝐿[𝑞;𝑝]$$ kind of abhors regions where $$𝑞(𝑥)$$ have
non-null mass and $$𝑝(𝑥)$$ has null mass. This might look like a bug,
but it’s actually a feature in certain situations.

If you’re trying to find approximations for a complex (intractable)
distribution $$𝑝(𝑥)$$ by a (tractable) approximate distribution $$𝑞(𝑥)$$
you want to be absolutely sure that any 𝑥 that would be very
improbable to be drawn from $$𝑝(𝑥)$$ would also be very improbable to be
drawn from $$𝑞(𝑥)$$. That KL have this property is easily shown: there’s
a $$𝑞(𝑥)𝑙𝑜𝑔[𝑞(𝑥)/𝑝(𝑥)]$$ in the integrand. When 𝑞(𝑥) is small
but $$𝑝(𝑥)$$ is not, that’s ok. But when $$𝑝(𝑥)$$ is small, this grows very
rapidly if $$𝑞(𝑥)$$ isn’t also small. So, if you’re choosing $$𝑞(𝑥)$$ to
minimize $$𝐾𝐿[𝑞;𝑝]$$, it’s very improbable that $$𝑞(𝑥)$$ will assign a
lot of mass on regions where $$𝑝(𝑥)$$ is near zero.

The Jensen-Shannon divergence don’t have this property. It is well
behaved both when $$𝑝(𝑥)$$ and $$𝑞(𝑥)$$ are small. This means that it won’t
penalize as much a distribution $$𝑞(𝑥)$$ from which you can sample
values that are impossible in $$𝑝(𝑥)$$.


text:
# Why aren't methanal and ethanal also ketones?

Why aren't the aldehydes methanal/formaldehyde and ethanal/acetaldehyde also ketones? Ketones are defined by replacing any H - C - H in an alkane with C=O, which is true for both of these: methanal replaces two hydrogen atoms in methane with C=O, while ethanal does it with ethane.

• They are not ketones because the carbonyl group is at a terminal position. In a ketone, both neighbouring atoms of the carbon in $\ce{C=O}$ need to be carbon atoms. In the aldehydes, one of the neighbours is a hydrogen atom. Nov 4 '16 at 11:31
• That definition of ketones is wrong! Nov 4 '16 at 12:09

Aldehydes deserve a different name because they have different properties, for example being easily oxidized to acids, as in the Benedict test which distinguishes "reducing" sugars like glucose (an aldehyde) from non-reducing ones like fructose (a ketone). The relation between aldehydes and ketones is like the relation between alcohols and ethers, both of which can be described as R-O-R, but the properties are significantly different when one of the R's is a hydrogen.

According to the Glossary of class names of organic compounds and reactivity intermediates based on structure (IUPAC Recommendations 1995), ketones are defined as follows:

ketones:
Compounds in which a carbonyl group is bonded to two carbon atoms: $\ce{R2C=O}$ (neither $\ce{R}$ may be $\ce{H}$). NOC Rule C-311.1. (…)

The mentioned nomenclature of organic chemistry (NOC) Rule C-311.1 refers to the obsolete 1979 IUPAC recommendations:

311.1 – The generic name “ketone” is given to compounds containing an oxygen atom doubly bound to a single carbon atom with the carbonyl group $\ce{>C=O}$ joined to two carbon atoms. (…)

The corresponding rule in the also obsolete 1993 IUPAC recommendations reads:

R-5.6.2.1 Ketones. The generic term “ketone” refers to compounds containing a carbonyl group, $\ce{>C=O}$, joined to two carbon atoms. (…)

The current version of Nomenclature of Organic Chemistry – IUPAC Recommendations and Preferred Names 2013 (Blue Book) refers to the definition of the 1995 glossary of class names:

P-64.1.1 Ketones are defined classically as compounds in which a carbonyl group is bonded to two carbon atoms: $\ce{R2CO}$ (neither $\ce{R}$ may be $\ce{H}$). (…)

All definitions include the criterion that the carbonyl group is bonded to two carbon atoms. Since in methanal (formaldehyde) as well as in ethanal (acetaldehyde) the carbonyl group is not bonded to two carbon atoms, these compounds are not ketones.

Functional groups are identified based on their characteristic reactions. Aldehydes and ketones are structurally similar, and reactivity is certainly closely related for both groups. However, there are reactions where the outcome is very different for aldehydes than for ketones. Here is one of them:

Oxidation

Aldehydes react with a variety of oxidizing agents to form carboxylic acids (formaldehyde is often over-oxidized to carbon dioxide).

$$\ce{RC(O)H ->[\ce{CrO3}][\ce{H2SO4}] RCO2H}$$

Ketones, on the other hand, are hard to oxidize. Acetone (dimethyl ketone, 2-propanone) is sometimes used as a cosolvent in the chromic acid oxidation (above).

$$\ce{RC(O)R ->[\ce{CrO3}][\ce{H2SO4}]} \text{no reaction}$$

That is not to say that ketones cannot be oxidized, but different reagents are needed:

$$\ce{RC(O)R ->[\ce{RCO3H}] RCO2R}$$


text:
# A Parameter Toolbox

The last little project I did, parts of it below, took about 12-15 hours in Visual Studio (COM) and on completion I dumbed it down and converted it to Excel VBA-Autocad, about 3-4 hours for that. The code does not have to rewritten. The improvements of VB.net have to be undone.

Visual studio is a vastly better programming environment than VBA. But the problem is distribution. If the distributed XLSM file has the wrong version of autocad referenced, Excel will open the dialog to change it when first opened. With an EXE its just a dead end. Netload does seem to have some flexibility in this area. I have been working on it. I think I have some success driving parts in autocad from a form with a draw button and textbox number input with autocad.net, so that is the next direction.

Nevertheless I am using Visual Studio to automate Autocad with COM (ActiveX) and, so far, it works great. Essentially I am getting full functionality just by pasting from excel VBA and correcting the syntax changes. But I can’t share it with any other autocad version.

Below are some thoughts on developing a Visual Studio toolbox template and typical methods for multi-view 2D parametrics, with COM, not dotnet.

The basic starting technique is to sketch the part a view at a time on an XY grid. On the sketch, draw a vertical line at each X coordinate needed, X1, X2 etc. Do the same thing for the Y axis. Now link those to the parameters.

For instance a sheetmetal formed pan with a double bend at each side – You will have LENGTH, WIDTH, EDGE and FLANGE. The entire thing is described with 4 variables.

to draw a face view –

X0 = 0
X1 = FLANGE
X2 = WIDTH – FLANGE
X3 = WIDTH

The Y values are the same except LENGTH is substituted for WIDTH.

Then put those together to create point objects – an array of 3 doubles. Its much simpler to create the x, y values first then create the point objects.

in this simplest case, I have a box sub and the creation of the points is buried in there.

a slightly more complicated side view starts to show how this helps manage the complexity.

While that is an ugly point list, hard to read, it was easy to write. The figure is double line, in case its hard to tell. I am hard coding the thickness at 1/16 inch but that could also be a variable. Start at X1,Y1 and go counter-clockwise around.
In a multi-view drawing, how do we get the side view out to the side? we draw it in place by just adding a displacement to the X values. If the view is above, we add to the Y values. If its up and over, we add to both.

The displacement will vary on a lot of factors, mainly the dimensions of the front view and the dimension space.

Without dimensions, its just a sketch. The main programming toolbox for simple 2D parametrics contains wrappers or helpers for

Line
Polyline
Circle
Slot (in this particular example)
A point creator (essential with VBA but not hardly necessary with VB.NET)
Selection Sets (for making a Block)
Mtext
Linear Dimension, horizontal and vertical
Making a Block

Make the form look the way you want, change all the textbox label text at the same time with the idea they will all become global variables. Move things around, then change all the textbox names at the same time. Declare global variables for everything on the screeen, and make a sub to Get_All_Vars. Load defaults either by typing values into the properties box or in form_load.

I have one button to draw all views, with check boxes to turn on or off. the button is simple.

   Private Sub Btn_Draw1_Click(sender As Object, e As EventArgs) Handles Btn_Draw1.Click
get_all_vars()  'get all vars from form
draw_init()     'set layer, dimstyle

If g_v1 Then view1()
If g_v2 Then view2()
If g_v3 Then view3()
If g_v4 Then view4()
If g_v5 Then view5()

acadApp.Update()
End Sub

Sub draw_init()
pt0 = Pt(0, 0, 0)
acadDoc.SetVariable("clayer", "0")
acadDoc.SetVariable("textstyle", "ArialN")

'g_sc is from form
Dim str As String = "PP-" & g_sc
acadDoc.ActiveDimStyle = acadDoc.DimStyles.Item(str)
acadDoc.SetVariable("LTSCALE", 0.5 * g_sc)
End Sub

Get_all_vars and draw_init are in the button, so the user can change the form and draw. Everything read in from the form is saved to a global variable. This makes it easier, there is no decision making over how to pass necessary variables. This is a small program.

Another expediency is the loading of drawing elements. I like to be able to start a program like this from a completely blank drawing. I load in a template drawing when the form loads. The template drawing has layer, dimension style, and text style information only. I have a half dozen dimension styles, all identical except for the dimension scale, and I name them pp-12, pp-16, pp-24 etc and set to the proper one from the scale on the form.

    Sub Insert_delete()
Dim strpath As String = "c:\prog\acad\"
Dim strfile As String = "pnl_template.dwg"
pt0 = Pt(0, 0, 0)
Dim blockrefObj As AcadBlockReference
blockrefObj = acadDoc.ModelSpace.InsertBlock(pt0, strpath & strfile, 1, 1, 1, 0)
blockrefObj.Delete()
End Sub

The first thing that has to be done is make a connection to autocad. you cannot make any autocad moves before connecting. Start_cad is called from Form_Load. It has to be first and it doesnt need to occur everytime the draw button is pushed.

 Public Sub start_cad()
m_ProgID = "AutoCAD.Application.22"
Call Connect_acad(m_ProgID)

Insert_delete()

End Sub

Public Sub Connect_acad(strProgID As String)
acadApp = Nothing
'Dim strProgId As String = "AutoCAD.Application.22"

Try         '' Get a running instance of AutoCAD
'acadApp = GetObject(, strProgId)
acadApp = CType(GetObject(, strProgId), AcadApplication)

Catch
Try     '' Create a new instance of AutoCAD
acadApp = CType(CreateObject(strProgId), AcadApplication)

Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
End Try

acadApp.Visible = True  '' Display the application
' MsgBox("Now running " & acadApp.Name & " version " & acadApp.Version)

'load whatever globals needed based on acadapp
acadDoc = acadApp.ActiveDocument
acadMs = acadApp.ActiveDocument.ModelSpace
ThisDrawing = acadApp.ActiveDocument

End Sub

the actual drawing subs are called View1, View2 etc. that is where we declare x and y values and branch off to the wrappers and helpers.

Function Line1(pnt1() As Double, pnt2() As Double, Optional strlayer As String = "none") As AcadLine
' line wrapper absolute pt args with optional layer
Dim lineobj As AcadLine
lineobj = acadDoc.ModelSpace.AddLine(pnt1, pnt2)

If strlayer <> "none" Then
lineobj.Layer = strlayer
End If
g_pt = pnt2
g_line = lineobj
Return lineobj
End Function

Sub Mtxt1(ptx() As Double, dblwidth As Double, str As String, Optional height As Double = 0.125, Optional layer As String = "0")
'uses optional height , layer
g_mtxt = acadDoc.ModelSpace.AddMText(ptx, dblwidth, str)
g_mtxt.Layer = layer
g_mtxt.Height = height
End Sub

Sub dimh(pt1() As Double, pt2() As Double, dimlocpt() As Double, Optional stylename As String = "none")
Dim dimObj As AcadDimRotated
dimObj = acadDoc.ModelSpace.AddDimRotated(pt1, pt2, dimlocpt, 0)
dimObj.Layer = "Dim"

If stylename <> "none" Then
dimObj.StyleName = stylename
dimObj.Update()
End If
g_dim = dimObj
End Sub

Sub dimv(pt1() As Double, pt2() As Double, dimlocpt() As Double, Optional stylename As String = "none")
Dim dimObj As AcadDimRotated
dimObj = acadDoc.ModelSpace.AddDimRotated(pt1, pt2, dimlocpt, PI / 2)
dimObj.Layer = "Dim"

If stylename <> "none" Then
dimObj.StyleName = stylename
dimObj.Update()
End If
g_dim = dimObj
End Sub

I have found it easier to have separate subs for vertical and horizontal dims. With dimensions the endpoints are pretty straightforward, but the dimension line also has to be located. In old lisp routines, I always queried the dimstyle to see what the dimscale was. a half inch is a good distance to use between the part and the dimension line and between dimension lines. this is scaled times the overall scale factor, which is a textbox on the form. the location of the side views also use the scale to know how much space the dimensions take.

The dimension lines can be located with a Polarpoint type function. This works just like autocad’s built-in Utility.PolarPoint

Function ppt(pnt() As Double, ang As Double, dist As Double) As Double()
Dim pnt1() As Double
Dim x, y As Double
x = dist * Math.Cos(Deg2rad(ang))
y = dist * Math.Sin(Deg2rad(ang))
pnt1 = Pt(pnt(0) + x, pnt(1) + y, 0)
Return pnt1
End Function

if we are dimensioning a box with corners at pt0,1,2,3
g_sc is a global scale variable from form (default 16).

Dim spc As Double = 0.5 * g_sc

pt0 = Pt(0,0,0)
pt1 = Pt(pnl_wid, 0, 0)
pt2 = Pt(pnl_wid, pnl_len, 0)
pt3 = Pt(0, pnl_len, 0)

dimh(pt0, pt1, ppt(pt0, 270, 2 * spc))
dimv(pt1, pt2, ppt(pt1, 0, 2 * spc))
dimh(pt3, pt2, ppt(pt3, 90, 2 * spc))
dimv(pt0, pt3, ppt(pt0, 180, 2 * spc))

Since these are overall dimensions, that puts them two spaces away so we can get another line in closer for details.

A basic tool for putting in a variable number of holes or slots at regular intervals and centering them on an any-size edge, is here,
L = N * C + 2R

I like to block drawing elements that are supposed to stay together. The front view of these panels are often put together side by side to form walls. if a block is made the assembly can be put together with ease. making a block in autocad activex is usually described as drawing in a BlockSpace, just like you would otherwise draw in a ModelSpace. That sounds fine in theory, but in practice it presents a problem to the wrapper helpers who all have something like

lineobj = acadDoc.ModelSpace.AddLine(pnt1, pnt2)

built into them. In Lisp i did have a switch on the argument list to draw in either ms or bs. in vb i am not sure that could be made to work so easily. Fortunately there is another method, and it allows much more flexibility.

the gist of the code is this

 Dim B1 As AcadBlock
B1 = acadDoc.Blocks.Item(strName)
Dim items(i) As AcadEntity
'populate a selection set
'transfer the selection set to array Items
acadDoc.CopyObjects(items, B1)

With that method we can draw in modelspace, select the items into a selection set with crossing or window, and send the selection set to the block making routine.

When making blocks there are 3 possible scenarios,
– the block name is not found and there are no complications, the new block is made, the items erased that formed the block and the block inserted,
– the block name is found but the block is not currently inserted, the old block definition can be deleted and proceed as above.
– the block name is found and there is an insert on the drawing, a message box is raised telling the user the block name is in use, the individual items are left on the screen, but there is no attempt to block.

Make_Block is a boolean function, so it indicates to the calling program whether it was successful or not. if succesful the calling program deletes the entities and inserts the block, if not then it does nothing.

the Try Catch error checking in VB.NET made this part of the code simpler than VBA.

    Function Add_ss(strName As String) As AcadSelectionSet
'adds new empty named selection set
Dim ss As AcadSelectionSet
Try
ss = acadDoc.SelectionSets.Item(strName)
ss.Clear()
Catch
'accessing ss created an error
ss = acadDoc.SelectionSets.Add(strName)
End Try
Return ss
End Function

'' function ss_x - return selection set from crossing window
Function ss_x(ss As AcadSelectionSet, pt1() As Double, pt2() As Double) As AcadSelectionSet
'items not visible do not select
acadApp.Update()
acadApp.ZoomAll()
ss.Select(AcSelect.acSelectionSetCrossing, pt1, pt2)
Return ss
End Function

Sub make_block_assy(strblk As String, pnt1() As Double, pnt2() As Double)
Dim sset As AcadSelectionSet
sset = Add_ss("SSBLOCK")
sset = ss_x(sset, pt1, pt2)

Dim result As Boolean
result = Make_blk(sset, strblk)

If result Then
sset.Erase()
sset.Clear()
sset.Delete()
g_entity = CType(acadDoc.ModelSpace.InsertBlock(pt0, strblk, 1, 1, 1, 0), AcadEntity)
g_entity.Layer = "0"
End If
End Sub

''  function make_blk
''  input - acadselectionset, str name of block
''  if new block name - make block, return true
''  if old block name with no inserts - delete old reference then make block, return true
''  if old block name with inserts - return false
Function Make_blk(ss As AcadSelectionSet, strName As String) As Boolean
Dim result As Boolean
Dim B1 As AcadBlock
Dim i As Integer

Try
B1 = acadDoc.Blocks.Item(strName)
Try
' Found block, try to delete"
B1.Delete()
Catch ex As Exception
' delete generated an error, do nothing and exit function
MsgBox("looks like there is an insert, I did not make a new block")
result = False
Return result
End Try
Catch ex2 As Exception
' no block found, adding
End Try

B1 = acadDoc.Blocks.Add(pt0, strName)
i = ss.Count - 1
Dim items(i) As AcadEntity
Dim item As AcadEntity

'loop ss and add acad entity objects to array
For i = 0 To ss.Count - 1
item = ss.Item(i)
items(i) = item
Next i

'populate block with items in the array
acadDoc.CopyObjects(items, B1)
result = True
Return result
End Function

I left out a few details, I have 5 views drawn, the 6th would be a flat pattern layout, before bending.

# A Replacement for VB Evaluate(string)

To graph a function we need to evaluate a string into its math equivalent. Excel VBA has the Application.Evaluate method which takes a variant for an argument and will evaluate a wide range of math symbols, with or without quotations – whatever is between the parentheses. In Visual Studio that doesn’t exist. We want to type a function (the right side of Y = some expression of X) into a textbox on a form, save it to a string variable, then calculate the value to a double for a range of X values. For instance,

strfunc = “X^3 – 3*X^2 + 2*x + 2”

A loop calculates X and Y values starting at X minimum, incrementing by a small X increment, ending at X maximum, and saving all the values to an array to be an argument for AddLightWeightPolyline.

the number of points to be stitched into a graph is calculated –
numpts = CInt((Xmax – Xmin) / Xinc) ‘number of line segments

there is always one more point than line segments
numpts = numpts + 1

the array of doubles is sized –
ReDim Pt(0 To numpts * 2 – 1) ‘store x and y for one pt

after the number of points has been calculated, and the array is ready, the loop is

For i = 1 To numpts
x = Xmin + ((i - 1) * Xinc)
y = eval_func(strfunc, x)
pt(i * 2 - 2) = x
pt(i * 2 - 1) = y
Next i

X is recalulated each time through the loop. Rather than adding the increment to a running sum, its more accurate to use the loop counter to multiply the increment, because of the imprecision of doubles. With odd numbers you might eventually run one cycle short or long. The loop counter should always be an integer. Calculation of Y is handed off to a function with the function string and the current value of X. The function substitutes the numerical value of X whereever X the symbol appears.

Debug.Print strfunc
strfunc = Replace(strfunc, “x”, x, , , vbTextCompare)
Debug.Print strfunc

the first time thru where X is at the starting value of, say, -6, the string and the modified string look like –

X^3 – 3*X^2 + 2*x + 2
-6^3 – 3*-6^2 + 2*-6 + 2

then the final scalar value is calculated and the value returned as Y.

dbl_result = Evaluate(strfunc)

This code was being run from Excel. Evaluate was a method of the top level Application.

For Visual Studio VB.Net we need a replacement for Evaluate.

A lot of people have asked this question. There are quite a few homebuilt parser class solutions. Another method is to link to another language and use its Eval method. A quick easy solution was found, credit to user kleinma

https://www.vbforums.com/showthread.php?412232-RESOLVED-02-03-Question-about-using-VBScript-(Eval)-in-VB-NET

As kleinma says, “Set a reference in your app to “Microsoft Script Control 1.0″ It is under the COM tab in references, not in the .NET tab”

A lot of testing will show if its a decent fix or just the first try.

    Public Xmin As Double
Public Xmax As Double
Public Xinc As Double
Public Ylim As Double
Public g_stop As Boolean
Public g_err_counter As Integer

Function calc_xy(strfunc As String) As Double()
'returns an array of x and y doubles
'Xmax, Xmin, Xinc, Ylim are all assumed to have values
Dim x, y As Double
Dim i, numpts As Integer
Dim Pt() As Double

g_err_counter = 0
g_stop = False

numpts = CInt((Xmax - Xmin) / Xinc) 'number of line segments
numpts = numpts + 1   'one more pt than line segment
ReDim Pt(0 To numpts * 2 - 1) 'store x and y for one pt

For i = 1 To numpts
x = Xmin + ((i - 1) * Xinc)
y = eval_func(strfunc, x)

If g_stop Then  'if eval_func set g_stop then
MsgBox("errorcounter at 3 - exiting")
Exit For
End If
Pt(i * 2 - 2) = x
Pt(i * 2 - 1) = y
Next i

Return Pt
End Function

Function eval_func(ByVal strfunc As String, x As Double) As Double
'returns a double
'on error returns Ylim but sets a flag to stop after 3 errors
'which would indicate a bad formula
'one or two error is ok because havent solved the mid-graph asymptote yet
Dim result As Double
strfunc = Replace(strfunc, "x", x.ToString, , , vbTextCompare)

Dim SC As New MSScriptControl.ScriptControl
SC.Language = "VBSCRIPT"
Try
result = Convert.ToDouble(SC.Eval(strfunc))
Catch ex As Exception
MessageBox.Show(ex.GetType.ToString & " " & ex.Message)
g_err_counter = g_err_counter + 1
If g_err_counter > 2 Then
g_stop = True
End If
result = Ylim
End Try

Return result
End Function

# 3 Equations in 3 Unknowns

“The central problem of linear algebra is the solution of simultaneous linear equations. The most important case is when the number of unknowns equals the number of equations… we begin in three dimensions.” Gilbert Strang – Linear Algebra and its Applications

Ax + By + Cz = D is a linear equation which can be represented by a plane. The intersection of 3 planes at a single point is the solution of the 3 equations used to plot the planes.

its hard to show the intersection of 3 planes with a static image. the Region object is trimmable with the command SurfTrim.
this is the very first example set of equations from Strang’s (old version) book.

A plane is defined by 3 points. But the equation for the plane is more directly derived from a single point and a vector that is orthogonal (perpendicular) to the plane. The dot product of two vectors is

$\mathbf{a} \cdot \mathbf{b} = |\mathbf{a}| |\mathbf{b}| \cos \theta$

so if the angle between the vectors is 90 degrees, the scalar dot product is zero. The dot product also has the alternative computation that if vector a = (a1, a2, a3) and b = (b1, b2, b3) then

$\mathbf{a} \cdot \mathbf{b} = (a1 \ast b1) + (a2 \ast b2) + (a3 \ast b3)$

if N is the vector perpendicular to the plane,

$\mathbf{N} = \begin {pmatrix} A \\ B \\ C \\ \end{pmatrix}$

if P1 is the specific point in the plane, and P is a generic point in the plane,

$\mathbf{P1} = \begin {pmatrix} x1 \\ y1 \\ z1 \\ \end{pmatrix}$

$\mathbf{P} = \begin {pmatrix} x \\ y \\ z \\ \end{pmatrix}$

then a vector from P1 to P is (P – P1) and the dot product of N and this line is zero.

$\mathbf{N} \cdot (\mathbf{P} - \mathbf{P1}) = 0$

according to the rules, that can be written as

$\mathbf{N} \cdot \mathbf{P} = \mathbf{N} \cdot \mathbf{P1}$

which becomes

$Ax + By + Cz = A(x1) + B(y1) + C(z1)$

the numbers on the right have specific values, because we are using a specific point and a specific vector, so we can just call those D

$Ax + By + Cz = D$

which is the standard equation for a plane. The constants A B and C are from the normal vector.

In linear algebra, we are usually given 3 of these equations, and asked to solve it, which means find the intersection of the planes, if it exists. To plot from this equation, Ax + By + Cz = D, where A,B,C and D have actual values, to autocad or any other graphic method, we need three points. About the only way to do that i know is to substitute values. In the most general case where neither A, B or C is zero, the plane intersects all 3 axes, and the 3 intersection points can be found by solving the equation with two variables of x, y and z set to zero. Where one variable of A, B, and C is set to zero, the plane is parallel to the missing axis variable. Where two variables are zero the plane is parallel to both. Its a little tedious, but you just set up tables and solve the equation in the abstract with the missing variables visualizing the plane. Then a select case statement will be the gateway to the actual drawing of the plane.

The other method needed – besides plotting given only the standard equation – is deriving the equation from 3 given points. For that the cross product is essential. 3 non-linear points form a triangle, from which you can see 2 vectors in the plane. The cross product of 2 vectors is a third vector that is orthogonal (perpendicular) to both of them. the cross product gives you the normal vector, with ABC direction numbers. Then you use one of the 3 points, the normal vector, and derive the equation.

all this is covered in the latter third of a full calculus book, the chapter on vectors in space, or 3D vectors, or geometry of space. its also in analytic geometry books and implied or explained in linear algebra books. I am making a linear algebra homework tool.

In the most general case where neither A, B, or C is zero, the axis intercepts are calculated, a triangle can be drawn, and it can be filled with a Region object. If D is zero the plane goes thru the origin, and that is also a special case, the 3 intercepts are the same.

If you are given the std equation, you have the normal vector, but if you are given the 3 points in the plane, you need the normal vector. That is a pretty simple operation with the cross product. the cross product is a pretty fussy formula, but once it is captured to a sub its easy to use.

    Function find_norm(ptA() As Double, ptB() As Double, ptC() As Double) As Double()
'given 3 points, not co-linear, find norm
Dim AB() As Double
Dim AC() As Double
Dim norm() As Double

AB = Minusv(ptB, ptA)
AC = Minusv(ptC, ptA)
norm = Cross_Product(AB, AC)

Return norm
End Function

Function Cross_Product(t() As Double, v() As Double) As Double()
Dim x, y, z As Double
x = t(1) * v(2) - t(2) * v(1)
y = t(2) * v(0) - t(0) * v(2)
z = t(0) * v(1) - t(1) * v(0)
Cross_Product = Pt(x, y, z)

Return Cross_Product
End Function

now having 3 points and a normal vector, its optional, but i find the centroid of the triangle as a convenient reference point. if the vertexes are F, G, H, the centroid is very simply (F + G + H) / 3. Now using a vector from the centroid to a vertex, and having the normal, you can once again use the cross product to find a vector orthogonal to both of them. For the purpose of creating a UCS (User Coordinate System) in the plane. Once you have created the UCS, its a simple matter to enlarge your plane, using a Circle center at the centroid, or a square or rectangle.

its a work in progress, here is current state of form. its not really easy to pick off the intersections graphically. the regions can be trimmed but i am going to look at other objects and methods.

# Converting Autocad VBA ActiveX to Visual Studio

The Autocad ActiveX and VBA Developer’s Guide, Work in Three Dimensional Space (chap 8 in the old print version), is available with 10 sample code programs here

also in your autocad installation as a CHM file, (very easy to work with)
ProgramFiles\Common Files\Autodesk Shared\acadauto.chm

these sample programs paste in to Visual Studio with a few but not too many problems. Below is a screenshot of the first one. On the left is the virgin code. On the right is the corrected version which runs as intended.

Visual Studio throws up 8 errors on paste. (see ThisDrawing discussion below)
Let and Set assignment is no longer supported. You simply delete them.
acRed and acBlue is not declared. Hovering over the word acRed, Visual Studio suggests the fix, add the namespace ACAD_COLOR
Variant is no longer a supported type: Use the Object type instead.

Changing Variant to Object does eliminate the error on that line, but creates errors where it is accessed. Arrays are an area where dot.net has fixed logical inconsistencies in VBA. Autocad declared a return value of variant because static arrays could not accept an assigment. Dynamic arrays could accept assignment, but that was not in the very first version of VBA, and apparently never made it into the Autocad ActiveX implementation. There is no longer a distinction in dot.net between dynamic and static arrays.

We know the point data for polylines is a Double, and we know the autocad Coordinates method will return a variable number of points, so lets declare the variable as we would a double type dynamic array.

Dim get2Dpts() as Double

now we get an error on assigment –
get2Dpts = pline2DObj.Coordinates
Option Strict On disallows implicit conversions from ‘Object’ to ‘Double’.

anytime you get that and you know your variables are convertible the solution is Ctype(var, type)
get2Dpts = CType(pline2DObj.Coordinates, Double())

Autocad VBA sample code references a variable called ThisDrawing which is always available in the VBA environment. From Visual Studio, I run a sub called Connect_Acad that makes the connection and uses a global AcadDocument variable which can be named ThisDrawing and that is what i have done here. It is added to the top of the sample code.

Make those changes and it runs as is.

There is a simplification on the array assignments available in Visual Studio. In VBA I made subroutines to try to make the awkward point data assigments flow easier. VB.Net has a good new array feature called an initialization list.

you can change all this –

Dim points2D(0 To 5) As Double
Dim points3D(0 To 8) As Double

‘ Define three 2D polyline points
points2D(0) = 1 : points2D(1) = 1
points2D(2) = 1 : points2D(3) = 2
points2D(4) = 2 : points2D(5) = 2

‘ Define three 3D polyline points
points3D(0) = 1 : points3D(1) = 1 : points3D(2) = 0
points3D(3) = 2 : points3D(4) = 1 : points3D(5) = 0
points3D(6) = 2 : points3D(7) = 2 : points3D(8) = 0

to this –

‘ Define three 2D polyline points
Dim points2D() As Double = {1, 1, 1, 2, 2, 2}

‘ Define three 3D polyline points
Dim points3D() As Double = {1, 1, 0, 2, 1, 0, 2, 2, 0}

side by side screenshots –

*******************
NewUCS
*******************
9 errors on paste
Set
Method arguments must be enclosed in parentheses.
acWorld and acUCS is not declared.

fix those and down to 4 all due to Variant.

Dim WCSPnt As Variant
Dim UCSPnt As Variant

Lets try that again where we change the variant array to its target double array.
Dim WCSPnt() As Double
Dim UCSPnt() As Double

Again we get an error where Autocad Utility Getpoint is returning an Object, originally it was a Variant. We know its a double array so we can use the Ctype function.

The other and last error though is on the boolean argument in Utility.TranslateCoordinates.
UCSPnt = ThisDrawing.Utility.TranslateCoordinates(WCSPnt, AcCoordinateSystem.acWorld, AcCoordinateSystem.acUCS, False)
Strict On disallows implicit conversions from ‘Boolean’ to ‘Integer’.

That makes me want to look at the ActiveX Reference Guide under Objects Utility TranslateCoordinates. Its a flag possible values are True or False but its a Long type not Boolean. it affects whether the first argument is treated as an absolute point value or a vector. i dont quite know why its implemented like that but i can go with the value zero to get the intent.

That allows another error which has been in the queue on the same line. which is fixed by the familiar Ctype function.
And now it runs.

Arrays in VB.Net are all normally zero-based (with some exceptions). So VBA declarations such as Dim pt (0 to 2) as double can be changed to Dim pt(2) as Double. But we can also use the initialization list to clean up.

change this –
Dim origin(0 To 2) As Double
Dim xAxisPnt(0 To 2) As Double
Dim yAxisPnt(0 To 2) As Double

origin(0) = 4 : origin(1) = 5 : origin(2) = 3
xAxisPnt(0) = 5 : xAxisPnt(1) = 5 : xAxisPnt(2) = 3
yAxisPnt(0) = 4 : yAxisPnt(1) = 6 : yAxisPnt(2) = 3

to this –
Dim origin() As Double = {4, 5, 3}
Dim xAxisPnt() As Double = {5, 5, 3}
Dim yAxisPnt() As Double = {4, 6, 3}

Sub Ch8_NewUCS()
Call Connect_acad()
Dim ucsObj As AcadUCS

Dim origin() As Double = {4, 5, 3}
Dim xAxisPnt() As Double = {5, 5, 3}
Dim yAxisPnt() As Double = {4, 6, 3}

' Add the UCS to the UserCoordinatesSystems collection
ucsObj = ThisDrawing.UserCoordinateSystems.Add(origin, xAxisPnt, yAxisPnt, "New_UCS")
' Display the UCS icon
ThisDrawing.ActiveViewport.UCSIconAtOrigin = True
ThisDrawing.ActiveViewport.UCSIconOn = True

' Make the new UCS the active UCS
ThisDrawing.ActiveUCS = ucsObj
MsgBox("The current UCS is : " & ThisDrawing.ActiveUCS.Name & vbCrLf & " Pick a point in the drawing.")

' Find the WCS and UCS coordinate of a point
Dim WCSPnt() As Double
Dim UCSPnt() As Double

WCSPnt = CType(ThisDrawing.Utility.GetPoint(, "Enter a point: "), Double())
UCSPnt = CType(ThisDrawing.Utility.TranslateCoordinates(WCSPnt, AcCoordinateSystem.acWorld, AcCoordinateSystem.acUCS, 0), Double())

MsgBox("The WCS coordinates are: " & WCSPnt(0) & ", " & WCSPnt(1) & ", " & WCSPnt(2) & vbCrLf &
"The UCS coordinates are: " & UCSPnt(0) & ", " & UCSPnt(1) & ", " & UCSPnt(2))
End Sub

*******************
TranslateCoordinates
*******************
8 errors on paste
Set, Arguments not enclosed in parentheses, unfound enumerations that need namespaces, and use of Variant arrays.

Dim firstVertex As Variant
firstVertex = plineObj.Coordinate(0)

looking up Polyline Object in the ActiveX Rerference Guide then clicking on Coordinate says the property value is a two or three element array of doubles.

change to –
Dim firstVertex() As Double
firstVertex = CType(plineObj.Coordinate(0), Double())

and
Dim coordinateWCS As Variant
coordinateWCS = ThisDrawing.Utility.TranslateCoordinates(firstVertex, AcCoordinateSystem.acOCS, AcCoordinateSystem.acWorld, False, plineNormal)

change to –
Dim coordinateWCS() As Double
coordinateWCS = CType(ThisDrawing.Utility.TranslateCoordinates(firstVertex, AcCoordinateSystem.acOCS, AcCoordinateSystem.acWorld, 0, plineNormal), Double())

    Sub Ch8_TranslateCoordinates()
Call Connect_acad()
Dim plineObj As AcadPolyline
Dim points() As Double = {1, 1, 0, 1, 2, 0, 2, 2, 0, 3, 2, 0, 4, 4, 0}

' Create a light weight Polyline object in model space
plineObj = ThisDrawing.ModelSpace.AddPolyline(points)

' Find the X and Y coordinates of the first vertex of the polyline
Dim firstVertex() As Double
firstVertex = CType(plineObj.Coordinate(0), Double())

' Find the Z coordinate for the polyline using the elevation property
firstVertex(2) = plineObj.Elevation

' Change the normal for the pline so that the difference between the coordinate systems is obvious.
Dim plineNormal() As Double = {0#, 1.0#, 2.0#}
plineObj.Normal = plineNormal

Dim coordinateWCS() As Double
coordinateWCS = CType(ThisDrawing.Utility.TranslateCoordinates(firstVertex, AcCoordinateSystem.acOCS, AcCoordinateSystem.acWorld, 0, plineNormal), Double())

' Display the coordinates of the point
MsgBox("The first vertex has the following coordinates:" & vbCrLf & "OCS: " & firstVertex(0) & ", " &
firstVertex(1) & ", " & firstVertex(2) & vbCrLf & "WCS: " & coordinateWCS(0) & ", " & coordinateWCS(1) & ", " & coordinateWCS(2))
End Sub

*************
Create3DMesh
************
here is one we can clean up quite a bit. it pastes in with only two errors, both trivial. It runs just by deleting the word Set, adding AcadApp. in front of ZoomAll and adding Connect_acad as the first line .
Here is the original VBA from Autocad.

Sub Ch8_Create3DMesh()
Dim meshObj As AcadPolygonMesh
Dim mSize, nSize, Count As Integer
Dim points(0 To 47) As Double

' create the matrix of points
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 2: points(4) = 0: points(5) = 1
points(6) = 4: points(7) = 0: points(8) = 0
points(9) = 6: points(10) = 0: points(11) = 1
points(12) = 0: points(13) = 2: points(14) = 0
points(15) = 2: points(16) = 2: points(17) = 1
points(18) = 4: points(19) = 2: points(20) = 0
points(21) = 6: points(22) = 2: points(23) = 1
points(24) = 0: points(25) = 4: points(26) = 0
points(27) = 2: points(28) = 4: points(29) = 1
points(30) = 4: points(31) = 4: points(32) = 0
points(33) = 6: points(34) = 4: points(35) = 0
points(36) = 0: points(37) = 6: points(38) = 0
points(39) = 2: points(40) = 6: points(41) = 1
points(42) = 4: points(43) = 6: points(44) = 0
points(45) = 6: points(46) = 6: points(47) = 0

mSize = 4: nSize = 4

' creates a 3Dmesh in model space
Set meshObj = ThisDrawing.ModelSpace. _
Add3DMesh(mSize, nSize, points)

' Change the viewing direction of the viewport
' to better see the cylinder
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1
NewDirection(1) = -1
NewDirection(2) = 1
ThisDrawing.ActiveViewport.Direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub

code that runs in visual studio

   Sub Ch8_Create3DMesh()
Call Connect_acad()
Dim meshObj As AcadPolygonMesh
Dim mSize, nSize, Count As Integer

Dim points() As Double =
{0, 0, 0,
2, 0, 1,
4, 0, 0,
6, 0, 1,
0, 2, 0,
2, 2, 1,
4, 2, 0,
6, 2, 1,
0, 4, 0,
2, 4, 1,
4, 4, 0,
6, 4, 0,
0, 6, 0,
2, 6, 1,
4, 6, 0,
6, 6, 0}

mSize = 4 : nSize = 4
' creates a 3Dmesh in model space
meshObj = ThisDrawing.ModelSpace.Add3DMesh(mSize, nSize, points)

' Change the viewing direction of the viewport
Dim NewDirection() As Double = {-1, -1, 1}
ThisDrawing.ActiveViewport.Direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
acadApp.ZoomAll()
End Sub

*************
GetUCSMatrix
************
sample code from object UCS method GetUCSMatrix in ActiveX Reference Guide

Here is the corrected code. I have added a loop to read and print the matrix values.
The orig program creates a new UCS, makes it active, then draws a circle. That illustrates that coordinate input from ActiveX is always interpreted as World coordinates (VBA ignores the current UCS). The program then runs

newMatrix = UCSobj.GetUCSMatrix
circleobj.Transformby(newMatrix)

which moves the circle from its world coordinates to the equivalent UCS coordinates.

We never have to examine the Matrix or know what its dimensions are. I added a loop to read it. The matrix is a square 4×4. It contains point values as columns. The bottom row seems to be unused.

col1 is the same data as the variable UCSXDIR, its the X vector from the UCS origin.
col2 is the same data as the variable UCSYDIR, its the Y vector from the UCS origin
col3 is the Z vector, which is obtainable from the XY vectors by the right hand rule.
col4 is the origin.

if we were writing our own matrix we would do

dim Matrix(3 , 3) as Double

or

dim Matrix( , ) as Double =
{ {1,0,0,2},
{ 0,1,0,2},
{ 0,0,1,0},
{ 0,0,0,1} }

these are direction vectors.
UCSXDIR = 1,0,0
UCSYDIR = 0,1,0
Z DIR = 0,0,1

absolute point
UCSORG = 2,2,0

this is not the whole story, Transformation Matrices are a fascinating topic in linear algebra. TransformBy has some useful examples, including scaling, which occurs on the main diagonal. ARX Developers Guide (search on transformation matrix) has better help page than ActiveX. First 3 columns are both rotation and scaling. last column is translation. Transformation matrixes can be combined so translation, scaling and rotation are all accomplished in a single operation.

TransformBy is a method of the elementary AcadEntity, meaning it is enabled for every object in the drawing.

Sub Example_GetUCSMatrix()
' This example creates a new UCS and finds the UCS matrix for it.
' It then creates a circle using WCS coordinates and
' transforms the circle for the UCS.
Call Connect_acad()

' Define a new UCS and turn on the UCS icon at the origin.
Dim ucsObj As AcadUCS
Dim origin() As Double = {2, 2, 0}
Dim xAxisPoint() As Double = {3, 2, 0}
Dim yAxisPoint() As Double = {2, 3, 0}

'Dim xAxisPoint() As Double = {4, 4, 0}
'Dim yAxisPoint() As Double = {0, 4, 0}

ucsObj = ThisDrawing.UserCoordinateSystems.Add(origin, xAxisPoint, yAxisPoint, "UCS1")
ThisDrawing.ActiveUCS = ucsObj

Dim vportObj As AcadViewport
vportObj = ThisDrawing.ActiveViewport
vportObj.UCSIconOn = True
vportObj.UCSIconAtOrigin = True
ThisDrawing.ActiveViewport = vportObj

' Create a circle using WCS coordinates
Dim circleObj As AcadCircle
Dim center() As Double = {1, 1, 0}
Dim radius As Double = 0.5
circleObj = ThisDrawing.ModelSpace.AddCircle(center, radius)
acadApp.ZoomAll()

' Get the UCS transformation matrix
Dim TransMatrix(,) As Double
TransMatrix = CType(ucsObj.GetUCSMatrix(), Double(,))

Dim str As String
Dim r, c As Integer
For r = 0 To UBound(TransMatrix, 1)
For c = 0 To UBound(TransMatrix, 2)
str = "r = " & CStr(r) & " c = " & CStr(c) & "   " & CStr(TransMatrix(r, c))
Debug.Print(str)
Next
Next

' Transform the circle to the UCS coordinates
MsgBox("Transform the circle.", , "GetUCSMatrix Example")
circleObj.TransformBy(TransMatrix)
circleObj.Update()
MsgBox("The circle is transformed.", , "GetUCSMatrix Example")
acadApp.Update()
End Sub

# How Do I Access Autocad Com Objects From Visual Studio?

I have stopped ignoring visual studio. I am having no issues accessing Com ActiveX objects from VB.Net with nearly the same code that works in VBA. I am not sure what all the naysaying is about. Every thread i have ever seen on running Com objects from Visual Studio says, Don’t do it, It’s a Bad Idea.

It seems to work fine.

as time goes by I may update this, but at this point –

Right click References in Solution Explorer, Add Reference, add the autocad type library.
To get the Autocad namespace to work across all modules, double click My Project in Solution Explorer and add Autocad to Imported Namespaces.

Get a book or study online the differences in syntax. They are pretty minor. The code editor is much improved. Arrays are a little simplified. Indexing is a little different, no static type. There is no variant type, but there is an object type that microsoft uses to read and write arrays to excel spreadsheets. (microsoft has a good one page link to connect to excel com objects HERE) Autodesk has no such single page that i can find, but here are some useful links.

http://help.autodesk.com/view/OARX/2019/ENU/?guid=GUID-BFFF308E-CC10-4C56-A81E-C15FB300EB70

http://help.autodesk.com/view/OARX/2019/FRA/?guid=GUID-C8C65D7A-EC3A-42D8-BF02-4B13C2EA1A4B

http://help.autodesk.com/view/OARX/2019/ENU/?guid=GUID-927E71C2-E515-438E-9D7A-246D97BEF93F

http://help.autodesk.com/view/OARX/2019/ENU/?guid=GUID-D1E1CE43-F42B-4D8E-9B42-FDA9D8CCB6B9

All methods to be capitalized. All arguments in parentheses. No set statements.
Sometimes you have to figure out how to get the namespace shortcuts to work. The error reporting in vs really helps.
The Try, Catch, End Try error system works more cleanly.
Many more tools to use with collections and array types.
There is a stricter approach to datatypes, a setting to relax it, but i have Option Strict On. this is where a book will help. 2012 books are cheap.

So far i have pasted in VBA code, made changes per notes above, and the same objects work with the same logic – lines, polylines, dimensions, blocks, ucs, text, selection sets.

Code below is for version 2018 (“Autocad.Application.22”)

Module Module_Connect_Acad

Public acadApp As AcadApplication
Public acaddoc As AcadDocument
Public acadms As AcadModelSpace

Public Sub Connect_acad()
acadApp = Nothing
Dim strProgId As String = "AutoCAD.Application.22"

Try         '' Get a running instance of AutoCAD
'acadApp = GetObject(, strProgId)
acadApp = CType(GetObject(, strProgId), AcadApplication)

Catch
Try     '' Create a new instance of AutoCAD
acadApp = CType(CreateObject(strProgId), AcadApplication)

Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
End Try

acadApp.Visible = True  '' Display the application
' MsgBox("Now running " & acadApp.Name & " version " & acadApp.Version)

'load whatever globals needed based on acadapp
acaddoc = acadApp.ActiveDocument
acadms = acadApp.ActiveDocument.ModelSpace
End Sub

End Module


text:
An Interesting Inverse Inequality: Proof

January 27, 2021

Here I show some of my internal thinking behind recent work where I prove a theorem that I stated as conjecture in an earlier, related manuscript. This arose from a thought I had a while ago: can we achieve a Gram-schmidt-like proces but without the use of inner products? If possible then I thought I could use it produce interesting new matrix factorizations. This proved hard to even make meaningful, what does orthogonality even mean without inner products? I give some of the context below, I state my generalization of “orthogonal” to settings without inner products, and then I prove that my algorithm achieves these pseudo-orthogonal results.

$$\newcommand{\norm}[1]{\left\lVert#1\right\rVert}$$

What does Gram-Schmidt do for us?

The Gram-Schmidt algorithm takes as input a sequence of linearly independent vectors $$A_1,A_2,\ldots,A_n$$ and produces a new set of linearly independent vectors $$Q_1,Q_2,\ldots,Q_n$$ such that $$span(Q_1,Q_2,\ldots,Q_n) = span(A_1,A_2,\ldots,A_n)$$ (see definition of span), and also $$Q_i \cdot Q_j = 0$$ whenever $$i\neq j$$ but $$Q_i \cdot Q_j = 1$$. Here I’m using the standard Euclidean dot product.

What is the utility of this orthogonality property? Orthogonality essentially makes it easy to accurately solve systems of linear equations $$\mathbf{Q}\mathbf{x}=\mathbf{b}$$ where $$\mathbf{Q} = [Q_1,Q_2,\ldots,Q_n]$$. This results from the simple consequence of orthogonality that $$\mathbf{Q}^T \mathbf{Q} = \mathbf{I}$$.

Thus to produce an algorithm that generalizes the Gram-Schmidt algorithm I should seek to reproduce this utility of orthogonality. The utility isn’t necessarily the vanishing dot products, but rather that it results in easily solved systems of linear equations. I give a precise mathematical way to determine how hard it is to solve linear systems with a matrix: conditioning

Gram-Schmidt without inner products: use norms instead

If we take $$\norm{ \mathbf{x} }_ 2 = \sqrt{\mathbf{x} \cdot \mathbf{x}}$$ then the matrix $$\mathbf{Q}$$ mentioned above has the property that $$\norm{ \mathbf{Q}\mathbf{x} }_ 2 = \norm{ \mathbf{x} }_ 2$$ for any $$\mathbf{x}$$ regardless of the input matrix $$\mathbf{A} = [A_1,A_2,\ldots,A_n]$$.

Generalizing orthogonality

I generalize this property as follows: Suppose that $$\norm{ \cdot }$$ is any norm and that $$F$$ is an algorithm (such as Gram-Schmidt) which given any input matrix $$\mathbf{A}$$ it outputs $$\mathbf{Q}=F(\mathbf{A})$$ such that $$span(Q_1,\ldots,Q_n) = span(A_1,\ldots,A_n)$$. Then there exists $$C_1>0,C_2>0$$ such that for every $$\mathbf{A}$$ and $$\mathbf{x}$$ we have

\begin{align} C_1 \norm{ \mathbf{x} } \leq \norm{ F(\mathbf{A})\mathbf{x} } \leq C_2 \norm{ \mathbf{x} } \end{align}

In other words: I require the algorithm $$F$$ to never result in matrices $$\mathbf{Q}=F(\mathbf{A})$$ that shrink or grow input vectors by too much. The amount that it may do this is known ahead of time by the constants $$C_1,C_2$$ and these do not depend on the input matrices $$\mathbf{A}$$. I now give an $$F$$ which achieves this and then prove it

The algorithm

Here I assume we have a sequence of $$n$$ linearly independent vectors $$A_1,\ldots,A_n$$ and that $$\norm{ \cdot }$$ is any norm whatsoever (not necessarily Euclidean). I define $$Q_1,\ldots,Q_n$$ inductively as follows:

\begin{align} Q_1 = \frac{1}{\norm{ A_1 }} A_1 \end{align}

and for any integer $$k>1$$ I define

\begin{align} c^k &= argmin_{u\in \mathbb{R}^{k-1}} \norm{A_{k-1} - \sum_{j=1}^{k-1} Q_j u_j } \\ q_k &= \sum _ {j=1} ^ {k-1} Q_k c_j ^k \\ \gamma_k &= \norm{ q_k } \\ Q_{k} &= \frac{1}{\gamma_k} q_k \end{align}

To put in words: We start by taking the first column of $$\mathbf{Q}$$ to be the normalized first column of $$\mathbf{A}$$. Every subsequent column of $$\mathbf{Q}$$ is the best approximation in the $$\norm{ \cdot}$$-norm of the previous columns to the next column of $$\mathbf{A}$$, and then normalized. Note that $$\norm{ Q_i }=1$$ for all $$i$$.

Proving key properties

I now show that the algorithm specified above results in constants $$C_1>0,C_2>0$$ such that for every $$\mathbf{A}$$ and $$\mathbf{x}$$ we have

\begin{align} C_1 \norm{ \mathbf{x} } \leq \norm{ F(\mathbf{A})\mathbf{x} } \leq C_2 \norm{ \mathbf{x} } \end{align}

The “less than or equal” part of this bound is known as a “forward” bound and is relatively straightforward. The “greater than or equal” part is known as an “inverse bound” and was extremely hard (for me) to prove. I start by proving the forward bound.

The forward bound

Suppose that $$\norm{ \cdot }$$ is a norm, that $$\mathbf{A}=[A_1,\ldots,A_n]$$ is a matrix with linearly independent columns, and that $$\mathbf{x}=[x_1,\ldots,x_n]$$ is a vector. Suppose further that $$\mathbf{Q}$$ is defined as above. Then using the triangle inequality and properties of norms we have

\begin{align} \norm{\mathbf{Q}\mathbf{x}} &= \norm{ \sum _{i=1}^n Q_i x_i } \\ &\leq \sum_{i=1}^n \norm{ Q_i x_i } \\ &\leq \sum_{i=1}^n \norm{ Q_i} \left | x_i \right | \\ &= \norm{ x } _1 \end{align}

we obtain $$C_2$$ by applying norm equivalence on finite dimensional spaces between $$\norm{ \cdot }_ 1$$ and $$\norm{ \cdot }$$.

The forward bound above is relatively straightforward in the sense that you only need apply standard linear algebra inequalities to achieve it. The inverse inequality on the other hand required a lot more lateral thinking to prove. I do this one next.

The inverse bound

Suppose that $$\norm{ \cdot }$$ is a norm, that $$\mathbf{A}=[A_1,\ldots,A_n]$$ is a matrix with linearly independent columns, and that $$\mathbf{x}=[x_1,\ldots,x_n]$$ is a vector. Suppose further that $$\mathbf{Q}$$ is defined as above.

I begin with a subtle fact: for every positive integer $$k\leq n$$ we have

\begin{align} \norm{\sum_{j=1}^k Q_j x_j} &= \norm{\sum_{j=1}^{k-1} Q_j + Q_k x_k } \\ &= \norm{\sum_{j=1}^{k-1} Q_j + \frac{1}{\gamma_k} \left (A_k - \sum_{j=1}^{k-1} Q_j c^k_j \right)x_k} \\ &\geq \norm{\frac{1}{\gamma_k} \left (A_k - \sum_{j=1}^{k-1} Q_j c^k_j \right)x_k} \\ &= \norm{Q_k x_k} \\ &= |x_k| \end{align}

where the inequality comes from the optimality property of $$c^k$$ and the final equation from $$\norm{Q_k}=1$$.

Now I define $$k$$ to be the largest integer which satisfies

\begin{align} |x_k| \geq \frac{1}{2^k} \norm{x}_ {\infty} \end{align}

In particular this means $$x_j < \frac{1}{2^j}\norm{x}_ {\infty}$$ for $$j>k$$. Thus we have

\begin{align} \norm{\sum_{j={k+1}}^n Q_j x_j} &\leq \sum_{j=k+1}^n \norm{Q_j x_j} \\ &\leq \sum_{j=k+1}^n \frac{1}{2^j} \norm{x}_{\infty} \\ &\leq \frac{1}{2^k} \norm{x}_{\infty} \\ &\leq |x_k| \\ &\leq \norm{\sum_{j=1}^k Q_j x_j } \end{align}

The above inequality will let us remove absolute values later because

\begin{align} \left | \norm{\sum_{j=1}^k Q_j x_j } - \norm{\sum_{j={k+1}}^n Q_j x_j} \right| = \norm{\sum_{j=1}^k Q_j x_j } - \norm{\sum_{j={k+1}}^n Q_j x_j} \end{align}

We now apply the reverse triangle inequality and get the following

\begin{align*} \norm{\mathbf{Q}\mathbf{x}} &= \norm{\sum_{j=1}^n Q_j x_j} \\ &= \norm{\sum_{j=1}^k Q_j x_j + \sum_{j=k+1}^n Q_j x_j} \\ &\geq \left | \norm{\sum_{j=1}^k Q_j x_j} - \norm{\sum_{j=k+1}^n Q_j x_j} \right | \text{ (by reverse triangle inequality)}\\ &= \norm{\sum_{j=1}^k Q_j x_j} - \norm{\sum_{j=k+1}^n Q_j x_j} \\ &\geq \norm{\sum_{j=1}^k Q_j x_j} - \sum_{j=k+1}^n \frac{1}{2^j}\norm{x}_{\infty} \\ &\geq \left | x_k \right | - \sum_{j=k+1}^n \frac{1}{2^j}\norm{\mathbf{x}}_{\infty} \\ &\geq \frac{1}{2^k}\norm{\mathbf{x}}_{\infty} - \sum_{j=k+1}^n \frac{1}{2^j}\norm{\mathbf{x}}_{\infty} \\ &= (\frac{1}{2^k} - \sum_{j=k+1}^n \frac{1}{2^j})\norm{\mathbf{x}}_{\infty} \\ &\geq \frac{1}{2^n}\norm{\mathbf{x}}_{\infty} \text{ (properties of geometric series) } \end{align*}

The proof is complete by appealing to norm equivalence between $$\norm{\cdot }$$ and $$\norm{ \cdot }_ {\infty}$$

Conclusion

I stated a simple inductive algorithm that takes a matrix $$\mathbf{A}$$ as input and produces a new matrix $$\mathbf{Q}$$ which satisfies bounded growth and shrinkage when applied to a vector $$\mathbf{x}$$. I quantified the growth and shrinkage factors $$C_1,C_2$$ by the above theorems and proved them. These factors are independent of $$\mathbf{A}$$. This suggests that the matrix $$\mathbf{Q}$$ is “well conditioned” in the sense that it is easy to solve linear systems $$\mathbf{Q}\mathbf{x} = \mathbf{b}$$ and does not get harder to solve this system even if we input a terribly conditioned $$\mathbf{A}$$. I consider this a useful step in the direction of generalizing the Gram-Schmidt algorithm so that it does not strictly require inner products.


text:
# How to find the perfect regularization number?

I have an issue!

Assume that we are going to solve $$Ax=b$$ but $$x$$ contains noise.To minimize that noise we can use regularization:

$$x = (A^TA + \lambda I)^{-1}A^Tb$$

Where $$\lambda$$ is a small number $$> 0$$, or sometimes $$\lambda$$ can be huge!

Here are three pictures of one situation where I solve $$Ax=b$$ with noise free and one $$Ax=b$$ with noise and without regularization and one with noise + regularization.

Noise free case: Here we can see that it works smooth. In this case, $$x$$ is a matrix because it contains two signals.

Here we are using 5% noise, that will cause much trouble. No regularization.

Here we are using 5% noise and a large number for regularization.

Question:

Is there a way to determine an optimized regularization parameter $$\lambda$$?

Source: I made a library named Mataveid and it's made for system identification. I have no problem with the noise actually, but I want to find a way to automize the choice of regularization parameter $$\lambda$$.

Approaches can be any of the following:

1. Model the noise that you expect, for ex: gaussian (least squares in Minimum variance unbiased estimator for a linear signal model in presence of gaussian noise). Based on this model try and estimate the noise variance, the regularization term should be close to noise varainace.

2. Deploy machine learning techniques based on signal parameters such as dynamic range, frqeuency, FFT noise floor etc. to estimate noise

3. Follow a recursive approach with adjusting the regularization to minimize a suitable objective, ex: gradient descent etc.

In general your regularization is as good as how close it is to the actual noise or estimation of noise. This goes back to the idea of whether a frequentist approach is better or Bayesian approach. The answers is if the modelling of the parameter is accurate to it's actual behaviour then the Bayesian approach is better but if you model a parameter with a distribution but it is actually not following that closely then Bayesian would lead to suboptimal result and better go for a frequentist approach.

• Thank you! What machine learning technique to you recommend? – Daniel Mårtensson Apr 27 at 11:18
• So if the noise variance is 100, then my $\lambda$ need to be 100 as well? – Daniel Mårtensson Apr 27 at 11:19
• Neural networks are known to be good for such problems as far as I know, I am sure there would be some other simpler ones, neural networks might be an overkill. Regarding noise varainace being 100, think of it this way, what if you knew the noise varainace was 100, then the best you would do to find x is to get a lmmse estimator, the lmmse estimator would have exactly the same expression as you have in your question with $\lambda$ replaced by $\sigma^2$, so yes, you substitute the nosie variance, after all that is the amount of noise that has effected the signal – Dsp guy sam Apr 27 at 11:23
• So the same noise power should be used in estimating the signal.hope that answers your question – Dsp guy sam Apr 27 at 11:24
• Can you show me an example ? – Daniel Mårtensson Apr 27 at 15:40


text:
## An owl is carrying a vole in its talons, flying in a horizontal direction at 8.3 m/s while 282 m above the ground. The vole wiggles free, an

Question

An owl is carrying a vole in its talons, flying in a horizontal direction at 8.3 m/s while 282 m above the ground. The vole wiggles free, and it takes the owl 2 s to respond. When it does respond, it dive at a constant speed in a straight line, catching the mouse 2 m from the ground (a) What is the owl’s dive speed? (b) What is the owl’s dive angle below the horizontal?(n radians) (c) How long, in seconds, does the mouse fall?

in progress 0
1 year 2021-09-02T07:49:49+00:00 1 Answers 4 views 0

1. a) 37.9 m/s

c) 7.56 s

Explanation:

a-c)

At the beginning, both the owl and the vole are travelling in a horizontal direction at a speed of

$$v_x=8.3 m/s$$

After the vole wiggles free, the owl takes 2 seconds to react; the horizontal distance covered by the owl during this time is

$$d_x = v_x t =(8.3)(2)=16.6 m$$

The vertical motion of the wiggle is a free fall motion, so it is a uniformly accelerated motion with constant acceleration

$$g=9.8 m/s^2$$ in the downward direction

The wiggle falls from a height of h’ = 282 m to a height of h = 2 m, so the vertical displacement is

s = h’ – h = 282 – 2 = 280 m

The time it takes the wiggle to cover this distance is given by the suvat equation:

$$s=u_y t – \frac{1}{2}gt^2$$

where $$u_y = 0$$ is the initial vertical velocity. Solving for t,

$$t=\sqrt{\frac{2s}{g}}=\sqrt{\frac{2(280)}{9.8}}=7.56 s$$

The owl must cover the vertical distance of 280 m in this time interval, so its vertical speed must be:

$$v_y=\frac{s}{t}=\frac{280}{7.56}=37.0 m/s$$

Therefore, the speed of the owl during the dive is the resultant of the velocities in the two directions:

$$v=\sqrt{v_x^2+v_y^2}=\sqrt{8.3^2+37.0^2}=37.9 m/s$$

b)

In part a-c, we calculated that the components of the velocity of the owl in the horizontal and vertical direction, and they are

$$v_x=8.3 m/s\\v_y=37.0 m/s$$

This means that the angle of the owl’s dive, with respect to the original horizontal direction, is

$$\theta=tan^{-1}(\frac{v_y}{v_x})$$

And substituting these values, we find:

$$\theta=tan^{-1}(\frac{37.0}{8.3})=77.4^{\circ}$$

And this angle is below the horizontal direction.

$$\theta=77.4\cdot \frac{2\pi}{360}=1.35 rad$$


text:
Using the method of${}^{86}\text{rubidium}$ extraction as developed by Sapirstein, we have studied the uptake of this isotope to measure changes in perfusion of normal mouse kidney, lung, liver, skin, and skeletal muscle after regional single doses of 240 kV X-rays estimated to be at or near the level of normal tissue tolerance for viscera. In the kidney, the extraction of isotope declines soon after irradiation and becomes significantly decreased from age controls by 2 months after 1100, 1500, or 1900 rads. This decrease in86 Rb extraction appears dose-dependent, continues to decline for at least 1 yr, and preceded histologic fibrosis by several months. The uptake of86 Rb in irradiated lung decreased significantly between 3 and 4 months after which it gradually returned to normal levels. No significant change in86 Rb extraction was seen in liver, skin or muscle after doses up to 1500 rads. Details of this isotopic technique and possible implications of perfusion changes in normal tissues for clinical radiation therapy are discussed.

This content is only available as a PDF.


text:
How to Use Pytorch Adam with Learning Rate Decay

If you’re using Pytorch for deep learning, you may be wondering how to use the Adam optimizer with learning rate decay. In this blog post, we’ll show you how to do just that!

Checkout this video:

Pytorch Adam: An Introduction

Pytorch Adam is one of the most popular optimization algorithms for training neural networks. It is a variant of stochastic gradient descent that helps to overcome some of the issues that can encountered when using traditional SGD.

Adam is typically used with a learning rate that is decayed over time. This can be done manually, but there are also a number of Learning Rate Schedules that can be used to automate this process.

Once you have selected your optimizer and learning rate, you will need to specify how the learning rate will be decayed. There are a number of options available, but the most common are:
-Exponential Decay
-Inverse Time Decay
-Polynomial Decay

Once you have selected your decay method, you will need to specify the parameters that will be used. For Exponential Decay, you will need to specify the initial learning rate and the decay rate. For Inverse Time Decay, you will need to specify the initial learning rate and the decay rate. And for Polynomial Decay, you will need to specify the initial learning rate, decay power, and end learning rate.

How to Use Pytorch Adam

Pytorch Adam is a optimization algorithm frequently used in training neural networks. It is similar to other optimization algorithms like gradient descent and stochastic gradient decent, but includes additional features like momentum and learning rate decay. In this article, we will show you how to use Pytorch Adam with learning rate decay.

First, we need to import the relevant libraries:

import torch
import torch.optim as optim
Then, we define ourAdam class:

class Adam(optim.Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8):
super(Adam, self).__init__(params)
self.lr = lr
self.betas = betas
self.eps = eps
def step(self):

for group in self.param_groups:

for p in group[‘params’]:

if p.grad is None: continue

grad = p.grad.data # here we get the gradient data

state = self.state[p] # here we get the current state

# Initialize the states if they don’t exist yet (first iteration)

if len(state) == 0:

state[‘step’] = 0

state[‘exp_avg’] = grad

state[‘exp_avg_sq’] = grad**2

continue # go to next param since first time iterating over this param

# next time iterating over this param (after first time), do Adam update on it – ie learn from past experience/iterations/data ! fractal knowledge/wisdom ! 🙂 Deep Learning 4 Life ! 🙂 ) ) ) ) )))) 😛 . . . . . njq8 }}}}}}}}}}}}))))))))))))))))))))0566313511411411411411411411411411411111197656011111101111101111111111322333333333334215917 chemicals 11 solids 22 gases 24 liquids 32 plasmas 194 excited states of atoms 208 stable isotopes of elements 2118 nuclides 1416 radioactive nuclides 235 nuclear transitions/decays 747 nuclear reactions 832 decay products of these reactions 3507 nuclides known to be unstable3703nuclides known to be metastable 104 man-made radioisotopes 10611 of all isotopes have never been observed in nature (most have extremely short half-lives) 26 chemical elements have no stable isotopes 28 chemical elements have no radioactive isotopes 50 chemical elements occur naturally in more than one stable isotope each 123 known island universes beyond the Milky Way galaxy 10000000000 Stars (mostly hydrogen and helium) 10782100000000 galaxies Estimated number of stars in the observable universe := 73 sextillion Estimated number of galaxies in the observable universe := 200 – 500 billion Estimated number of stars inthe Milky Way galaxy := 200 – 400 billion Typical number of stars innearby spiral galaxies similar to ours := 50 – 100 billion Number of stars contained inthe starburst region at the centerof our Milky Waygalaxy := 10 million Typical stellar luminosity (outer zone) inour spiral Milky Waygalaxy := 1 solar luminosity (= 3·1026 W or 3·1048 J/s) Diameterof our spiral Milky Waygalaxy := about 100 kly (= 9·1020 m or about 30 kpc; see also: 1 E15 m) Thicknessof galactic diskof our spiral Milky Waygalaxy := about 2 kly (= 1·1019 m or about 600 pc; see also: 1 E14 m 5•1028 kg Hydrogencyanide 70 K (–203 °C; –331 °F), 70 MPa Waterfreezing point 273 K (−0 °C; 32 °F), atmospheric pressure Icemelting point 273 K (−0 °C; 32 °F), atmospheric pressure

Pytorch Adam: Learning Rate Decay

Pytorch Adam is a great optimization algorithm that can be used for training neural networks. One advantage of using Pytorch Adam is the ability to set a learning rate decay schedule. This can be helpful in training your neural network more effectively.

To use Pytorch Adam with learning rate decay, you will first need to specify the decay rate and the number of steps to take before decaying the learning rate. You can do this by setting the ‘decay_rate’ and ‘decay_steps’ parameters in the ‘Adam’ class.

Once you have set these parameters, you will need to call the ‘step()’ function at each training step. This will update the learning rate based on the specified decay schedule.

Pytorch Adam is a great optimization algorithm that can be used for training neural networks. One advantage of using Pytorch Adam is the ability to set a learning rate decay schedule. This can be helpful in training your neural network more effectively.

To use Pytorch Adam with learning rate decay, you will first need to specify the Decay Rate (LR) and number of steps to take before decaying LR in the ‘Adam’ class. You can do this by setting the ‘decay_rate’ and ‘decay_steps’ parameters accordingly . For example, if we wanted to Decay LR by 0.1 every 5 steps , we would set those parameters as follows:

class Adam(object):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False):
self.params = list(params) # ensures module params are always iterable even if they are not passed as Iterable during init

self._lr = lr # Learning Rate – when no explicit lr is passed during optimizer construction we assume it’s “1”

self._betas = betas # stores beta values used for calculating running averages of gradient and squared gradient (momentum)

self._eps = eps # term added to denominator of second moment estimate (stabilizes calculation) – defaults to 1e-8 which is common practice

self._weight_decay = weight_decay # L2 regularization – if this value is non-zero L2 regularization penalty will be applied on model’s weights during backpropagation (eq-5 from paper)

self._amsgrad = amsgrad # AMSGrad variant of ADAM – from paper: https://openreview.net/forum?id=ryQu7f-RZ – only works with pytorch 0.4 or newer! – torchinfo checks context automatically and uses this flag if appropriate version detected def step(self):

for group in self._optimizer groups: weight_decay = group[‘weight_decay’] lr = group[‘ decayed_lr’] beta1 , beta2 , eps = group [‘betas’] amsgrad = group[‘amsgrad’] t = group[‘t’] ## load current optimizer values state = loadState(group) ## fallback .setdefault(‘step’, t + 1)) ++ t state[“step”] += 1 exp_avg , exp_avg_sqr , denom , step ; biasCorrection2 ; debias1frozen; debias2frozen 4 ## standard adam calculations performed below … if expAvgGrad == None : expAvgGrad [p] .data .zero_( ) running Avg unbiased Moment Estimate unbiased FIRST moment estimate : Exponential running avg ?? §§m_{t} := \alpha * m_{t-1} + (1 – \alpha)*g_{t}?? $$where ??alpha?? controls degree averaging performed on gradients ?? m?? stores avg momentum across timesteps$$V_{t} := \beta*V_{t-1} + (1-\beta)*g^2??  stores exponentially decaying running squared gradients across timesteps V storesvar wrt time denom : estimates variance like bias correction might intuitively think DeepMind tried both ways no diff they feell torch .addcmul_( pData , beta2frozenModifiedToNotDivideByHundred [p]Decayed ??g^{2} (- RunningAvgGradientSquaredTimesDecayingBetaSquared)?? ) var debiasing mechanism ultimately comes fromdenominator normalization term called “hat” -> so called Bias Correction torch .rsqrt_( denom

Pytorch Adam: Tips and Tricks

Adam is a great optimizer for training neural networks, but like any other optimizer, it can be tricky to use. In this article, we’ll go over some tips and tricks for using Adam with learning rate decay that will help you get the most out of your training.

Learning rate decay is an essential piece of using Adam (and any other optimizer) effectively. By decaying the learning rate, we can ensure that our optimizer doesn’t “overstep” and miss key minima in our loss function landscape. There are many ways to decay the learning rate, but a common one is to use a inverse time decay function:

lr = lr0 * (1 + alpha * t)^(-beta)

where lr0 is the initial learning rate, alpha and beta are hyperparameters, and t is the number of iterations. This function generally works well in practice, but you may want to experiment with different decay functions to see what works best for your problem.

Another important thing to keep in mind when using Adam is that it is important to initialize your optimization with a high enough learning rate. If your learning rate is too low, Adam will have a hard time finding good minima in your loss function landscape. In general, it is a good idea to start with a learning rate of 0.001 and then decrease it as needed.

Finally, one last thing to keep in mind when using Adam is that it tends to work best when used with batch sizes of 128 or more. When used with smaller batch sizes, Adam can have a hard time converging on a good solution. So if you’re having trouble getting Adam to work well on your problem, try increasing your batch size!

Pytorch Adam: Frequently Asked Questions

Pytorch Adam is a frequently used optimization algorithm for training neural networks. In this article, we will answer some of the most commonly asked questions about Pytorch Adam, including how to use it with learning rate decay.

What is Pytorch Adam?

Pytorch Adam is a tool that helps you train neural networks more effectively by optimizing the learning process. Adam stands for “Adaptive Moment Estimation”, and it is a variation of stochastic gradient descent that has been shown to be more effective in some cases.

How do I use Pytorch Adam with learning rate decay?

There are two ways to use Pytorch Adam with learning rate decay. The first is to include the “step” parameter in your Optimizer constructor. This will automatically Decay the learning rate every time the “step” number of iterations has been reached. The second way is to manually Decay the learning rate yourself by calling the “step” function on your Optimizer after each epoch.

Can I use Pytorch Adam with other optimization algorithms?

Yes, you can use Pytorch Adam with other optimization algorithms such as SGD, RMSprop, etc. However, keep in mind thatAdam is specifically designed for training neural networks, so you may not see any benefits from using it with other types of models.

Pytorch Adam: Resources

Pytorch Adam: Resources
Learning Rate Decay
In Pytorch, the learning rate decay is performed by the optimizer. Decay can be applied on a per-epoch basis or on a per-step basis. The per-epoch approach is generally preferred, but in some cases the per-step approach may be more appropriate.

There are two ways to specify the decay rate in Pytorch. The first is to specify a decay rate when creating the optimizer:

Adam(lr=0.001, betas=(0.9, 0.999), epsilon=1e-08, weight_decay=0)
The second is to specify a decay schedule when creating the optimizer:

Adam(lr=0.001, betas=(0.9, 0.999), epsilon=1e-08, weight_decay=0.00001, Schedule=’step’)
In both cases, the decay rate is specified as a parameter to the optimizer constructor. The first approach is simpler, but the second approach gives you more control over the decay schedule.

When using a decaying learning rate, it’s important to be careful not to let the learning rate decad too quickly. A good rule of thumb is to let the learning rate decay by half every 10 epochs or so.

Pytorch Adam: Final Thoughts

With Pytorch Adam, you can implement learning rate decay to help improve your training results. Be sure to experiment with different decay rates to find the one that works best for your dataset and training parameters.

Scroll to Top