Function with two arguments in R - r

I am trying to better understand functions and found an example online but can't get it to work.
I want to solve an equation a, and have two arguments v and r. v= 10 and r=3. Here is my code. What am I missing? Thanks for your insights.
solve <- function(r=3,v=10) {
a <- pi*r*(sqrt(r^2+(9*v^2)/pi^2*r^4))
}
return(a)
Based on inputs. Here is the updated code. But looks like the result is not accurate.
solve <- function(r,v){
a <- pi*r*(sqrt(r^2+(9*v^2)/pi^2*r^4))
return(a)
}
solve(3,10)
R is giving me a result of 810.4933. But the example says the result is 29.9906.
Here is the formula for A:
enter image description here

You need to know the order of operations within math expressions. If you read ?Ops (kind of obscure, granted), you'll see
2. Group '"Ops"':
• '"+"', '"-"', '"*"', '"/"', '"^"', '"%%"', '"%/%"'
• '"&"', '"|"', '"!"'
• '"=="', '"!="', '"<"', '"<="', '">="', '">"'
Which suggests that * and / are consecutive. Unfortunately, your denominator of
... / pi^2*r^4
is being interpreted as
(... / pi^2) * (r^4)
which brings r^4 into the numerator.
Add parens to enforce the order of operations.
.../(pi^2*r^4)

Related

Plothraw PARIGP (or similar) doesn't work (latexit crash)

I'm a new user of PARI/GP, and after writing my script, I wanted to make a graph of it. As my function take an integer and return a number, it's closer to a sequence. Actually, I didn't know how to do it, so I read the documentation of PARI/GP, and after that I made some test in order to obtain a graph from a list.
After reading an answer in stackoverflow (Plotting multiple lists in Pari), I wanted to test with the following code:
plothraw([0..200], apply(i->cos(i*3*Pi/200), [0..200]), 0);
But when I do it, it tries to open something on latexit, but then it crash and give me a problem report.
I didn't even know that I had an app named latextit, maybe it was install during the installation of PARI/GP. Anyway, how can I fix this?
PARI/GP definitely doesn't install latexit.
The way hi-res graphics work on the Win32 version of PARI/GP is to write down an Enhanced Metafile (.EMF) in a temp directory and ask the system to
"open" it. When you installed latexit it probably created an association in the registry to let it open .EMF files
i3Pi does not mean what you think, it just creates a new variable with that name. You want i * 3 * Pi instead.
The following constructions both work in my setup
plothraw([0..200], apply(i->cos(i*3*Pi/200), [0..200]), 0);
plothraw([0..200], apply(i->cos(i*3*Pi/200), [0..200]), 1);
(the second one being more readable because a red line is drawn between successive points; I have trouble seeing the few tiny blue dots)
Instead of apply, you can use a direct constructor as in
vector(201, i, cos((i-1) * 3 * Pi / 200))
which of course can be computed more efficiently as
real( powers(exp(3*I*Pi/200), 200) )
(of course, it doesn't matter here, but compare both commands at precision \p10000 or so ...)

selecting small vif variables in r

I am trying to write an r function to select covariates with small VIF.
Here is my code:
ea=read.csv("ea.csv")
library(car)
fullm<-lm(appEuse~.,data=ea)
cov<-names(ea)
ncov<-length(cov)
vifs<-rep(NA,ncov)
include<-rep(NA,ncov)
for (i in 1:ncov){
vifs[i]<-vif(fullm)[i]
if (vifs[i]<10){
include[i]<-cov[i+1]
}
}
Error in if (vifs[i] < 10) { : missing value where TRUE/FALSE needed
I was trying to set for loop from 1 to ncov-1, then got argument is of length zero.
Is there a way to go around it?
Could be wrong, but looks like you're trying to loop an if statement over a list of NAs:
vifs<-rep(NA,ncov)
is later referenced at
if (vifs[i]<10){
Could this be your issue?

How to feed data properly in tensorflow

I have been learning Tensorflow and understanding feed_dict has been a challenge. Take for example the following piece of code i am working on
p=0
self.sequence_length=25
with tf.Session() as sess:
init.run()
char_to_ix={ch:ix for ix,ch in enumerate(self.words)}
ix_to_char={ix:ch for ix,ch in enumerate(self.words)}
words_in_input=self.data[p:p+self.sequence_length]
inputs=[char_to_ix[ix] for ix in words_in_input]
words_in_target=self.data[p+1:p+self.sequence_length+1]
targets=[char_to_ix[ix] for ix in words_in_target]
onex=sess.run([selected_next_letter],feed_dict={self.X:inputs,self.y:targets})
p=p+1
This gives the error: Shapes of all inputs must match: values[0].shape = [25] != values[1].shape = []
However, when I edit the code to
with tf.Session() as sess:
init.run()
char_to_ix={ch:ix for ix,ch in enumerate(self.words)}
ix_to_char={ix:ch for ix,ch in enumerate(self.words)}
words_in_input=self.data[p:p+self.sequence_length]
inputs=[char_to_ix[ix] for ix in words_in_input]
words_in_target=self.data[p+1:p+self.sequence_length+1]
targets=[char_to_ix[ix] for ix in words_in_target]
for x,y in zip(inputs,targets):
onex=sess.run([selected_next_letter],feed_dict={self.X:x,self.y:y})
It executes.
My questions is: Is it possible to feed the whole list such as inputs and targets in the feed_dict or must I input it through a loop one by one. I ask this because the tutorials I have been reading, I see a whole list being passed in a feed_dict such as
loss_val = sess.run([train_op, loss_mean], feed_dict={
images_batch:images_batch_val,
labels_batch:labels_batch_val
})
Usually the reason for that error is because your input array(x) isn’t the same size as your labels array(y). As the error states it looks like your labels array is empty. Before doing anything tensorflowy make sure both x and y arrays have values in them and that they are of the same size.
To answer your question, yes you can use lists when training and is the preferred way of using tensorflow.

Sage TypeError positive characteristics not allowed in symbolic computations

I am new to sage and have got a code (link to code) which should run.
I am still getting an error message in the decoding part. The error trace looks like this:
in decode(y)
--> sigma[i+1+1] = sigma[i+1]*(z)\
-(delta[i+1]/delta[mu+1])*z^(i-mu)*sigma[mu+1]*(z);
in sage.structure.element.Element.__mul__
if BOTH_ARE_ELEMNT(cl):
--> return coercion_model.bin_op(left, right, mul)
in sage.structure.coerce.CoercionModel_cache_maps.bin_op
--> action = self.get_action(xp,yp,op,x,y)
...... some more traces (don't actually know if they are important)
TypeError: positive characteristics not allowed in symbolic computations
Does anybody know if there is something wrong in this code snipped? Due to previous errors, I changed the following to get to where I am at the moment:
.coeffs() changed to .coefficients(sparse=False) due to a warning message.
in the code line sigma[i+1+1] = sigma[i+1](z)\
-(delta[i+1]/delta[mu+1])*z^(i-mu)*sigma[mu+1](z); where the error occurs, i needed to insert * eg. sigma[i+1]*(z)
I would be grateful for any guess what could be wrong!
Your issue is that you are multiplying things not of characteristic zero (like elements related to Phi.<x> = GF(2^m)) with elements of symbolic computation like z which you have explicitly defined as a symbolic variable
Phi.<x> = GF(2^m)
PR = PolynomialRing(Phi,'z')
z = var('z')
Basically, the z you get from PR is not the same one as from var('z'). I recommend naming it something else. You should be able to access this with PR.gen() or maybe PR(z).
I'd be able to be more detailed, but I encourage you next time to paste a fully (non-)working example; trying to slog through a big worksheet is not the easiest thing to track all this down. Finally, good luck, hope Sage ends up being useful for you!

Convert Gray Code to Decimal in R

I have a set of 0's and 1's represented as a list initially created with sample(c(0,1), n, replace=TRUE), where n is the length of my binary number. I'm currently using a BCD converter to convert my binary number to a decimal number, this is seen here:
BCD.to.Decimal <- function(binaryNumb)
{
binaryLength = length(binaryNumb)
decimalNumb = 0
for(i in 1:binaryLength)
{
if ( binaryNumb[i] == 1)
decimalNumb = decimalNumb + 2^(binaryLength - i)
}
decimalNumb
}
I would like to instead use a GrayCode.To.Decimal converter which does the same job as my BCD.to.Decimal converter, but using Gray Code instead.
Note: Speed DOES matter for this, and I would like to do this in the most efficient way possible. I'm aware that my BCD converter is probably not the most efficient, its just the simplest, if you have a significantly more efficient way of handling BCD conversion I'd also be interested in hearing about that.
What is Gray Code?: http://en.wikipedia.org/wiki/Gray_code
Well, there's a conversion algorithm on that Wiki page, albeit in c so you'll have to port it.
Again on the wiki page, there's this link http://aggregate.org/MAGIC/#Gray%20Code%20Conversion
which lists a number of conversion algorithms, most of which appear pretty simple to code up.
BTW, oh whatever: GA::grey2binary and GA::binary2grey already exist. bah :-)
ETA - I was lucky enough to find this via Mr.Google but in general the package sos is a great R-search tool.
Here is the simple solution to my question, the algorithm ended up being much easier than it first appeared. The algorithm used can be found here.
GrayCode.to.Decimal <- function(grayNumb)
{
binaryNumb = vector("numeric",length(grayNumb))
binaryNumb[1] = grayNumb[1]
for (i in 2:length(grayNumb))
{
binaryNumb[i] = xor(grayNumb[i], binaryNumb[i - 1])
}
return(Binary.to.Decimal(binaryNumb))
}
This code will convert the code into binary where you can then use a binary conversion to convert it to a decimal number. I'm choosing to use the code provided by flodel in the comments section.
Binary.to.Decimal <- function(binaryNumb)
{
L = length(binaryNumb)
sum(2L^(seq_along(binaryNumb)-1L) * rev(binaryNumb))
}

Resources